0

我正在使用以下 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)

结尾

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

4

1 回答 1

1

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

于 2013-05-30T08:42:47.133 回答