我被困在一个我找不到任何理由或解决方案的问题。从SQL Server导出到Excel
我正在运行一个SQL脚本来将一些数据导出到Excel工作表。另一端有一个应用程序,用于读取和处理Excel工作表。
问题:列标题显示在底部,应用程序期望它们位于最上面一行。我无法改变应用程序的功能。
这在SQL 2005中工作正常,但我们最近更新到SQL 2012,这开始发生。
我还没有找到任何通过互联网来解决这个问题。
这是我执行
SELECT
@columnNames = COALESCE(@columnNames + ',', '') + '['+ column_name + ']',
@columnConvert = COALESCE(@columnConvert + ',', '') + 'convert(nvarchar(4000),'
+ '['+ column_name + ']' +
case
when data_type in ('datetime', 'smalldatetime') then ',121'
when data_type in ('numeric', 'decimal') then ',128'
when data_type in ('float', 'real', 'money', 'smallmoney') then ',2'
when data_type in ('datetime', 'smalldatetime') then ',120'
else ''
end + ') as ' + '['+ column_name + ']'
FROM tempdb.INFORMATION_SCHEMA.Columns
WHERE table_name = '##TempExportData'
-- execute select query to insert data and column names into new temp table
SELECT @sql = 'select ' + @columnNames + ' into ##TempExportData2 from (select ' + @columnConvert + ', ''2'' as [temp##SortID] from ##TempExportData union all select ''' + replace(replace(replace(@columnNames, ',', ''', '''),'[',''),']','') + ''', ''1'') t order by [temp##SortID]'
exec (@sql)
-- build full BCP query
DECLARE @bcpCommand VARCHAR(8000)
SET @bcpCommand = 'bcp " SELECT * from ##TempExportData2" queryout'
SET @bcpCommand = @bcpCommand + ' ' + @fullFileName + ' -T -w -S' + @serverInstance
EXEC master..xp_cmdshell @bcpCommand
的SQL脚本,TempExportData2
带列标题
如果您正在运行导致问题的SQL脚本,并且您没有向我们展示* SQL脚本*,您如何期待我们为您进行调试?我们不可能用我们看不到的代码来确定问题。我发现从SQL 2005到2012的转换极不可能导致列标题从顶部移动到底部,而不管脚本在做什么,而且我当然需要看到产生该问题的SQL脚本。 –
我已将查询添加到问题中。在我们更新到SQL 2012之前,它工作得很好,如果我在SQL 2005的旧实例中再次运行查询,它运行良好。但在2012年,它只是把它弄糟。 – savvyBrar
@KenWhite现在可以帮助查询吗? – savvyBrar