将SQL Server中的表导出到Excel

时间:2013-05-30 06:49:30

标签: sql sql-server excel export

我正在使用以下SP:

ALTER PROCEDURE [dbo].[FullExport]
(
@db_name as nvarchar(100),
@table_name varchar(100),   
@file_name  varchar(100)
)
as
Begin
//Generate column names as a recordset
DECLARE @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)

SELECT @columns=coalesce(@columns+',','')+column_name+' as '+column_name 
FROM information_schema.columns
WHERE table_name=@table_name

SELECT @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')

//Create a dummy file to have actual data
SELECT @data_file = substring(@file_name,1,len(@file_name)-    
charindex('\',reverse(@file_name)))+'\data_file.xls'

//Generate column names in the passed EXCEL file
SET @sql='exec master..xp_cmdshell ''bcp " SELECT * FROM
(SELECT '+ @columns+') as t"    queryout "'+@file_name+'" -c'''

exec(@sql)

//Generate data in the dummy file
SET @sql='exec master..xp_cmdshell ''bcp "SELECT * from '+@db_name+'..'  
+@table_name+'"   queryout "'+@data_file+'" -c'''

exec(@sql)

//Copy dummy file to passed EXCEL file
SET @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "' +
@file_name+'"'''

exec(@sql)

//Delete dummy file 
SET @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''

exec(@sql)

END

正在创建文件,但内容为空,有什么想法吗?

1 个答案:

答案 0 :(得分:1)

一开始你应该将你的列名称分隔为[包含空格的名称],但是我倾向于先找到虚拟文件的长度为零,然后运行在SQL Management Studio中生成的查询来查找它返回的行(如果有的话)以及它给出的错误消息