2015-05-20 120 views
-1

我被困在一个我找不到任何理由或解决方案的问题。从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带列标题

+1

如果您正在运行导致问题的SQL脚本,并且您没有向我们展示* SQL脚本*,您如何期待我们为您进行调试?我们不可能用我们看不到的代码来确定问题。我发现从SQL 2005到2012的转换极不可能导致列标题从顶部移动到底部,而不管脚本在做什么,而且我当然需要看到产生该问题的SQL脚本。 –

+0

我已将查询添加到问题中。在我们更新到SQL 2012之前,它工作得很好,如果我在SQL 2005的旧实例中再次运行查询,它运行良好。但在2012年,它只是把它弄糟。 – savvyBrar

+0

@KenWhite现在可以帮助查询吗? – savvyBrar

回答

0

我想我明白这个问题沿着保存数据:您在select into而不是使用order by在最后的select声明中。

你应该知道,内表中的数据被认为是unorderd和SQL Server(以及任何其他RDBMS我知道,其实)并不能保证,如果select语句不包含order by子句选择行的顺序。

为此,你应该[temp##SortID]列添加到您的##TempExportData2表,并用它来排序最后select声明:

SET @bcpCommand = 'bcp " SELECT * from ##TempExportData2 ORDER BY [temp##SortID]" queryout' 

因为你并不需要在输出查询栏,所以你可能要指定该select语句中的列名称。但是,如果它不会对读取excel文件或生成的数据的应用程序造成损害,那么我建议保留select *以使查询更具可读性。