简体   繁体   English

使用 OPENROWSET 将 SQL Server 导出到 Excel

[英]SQL Server export to Excel with OPENROWSET

I am successfully exporting to excel with the following statement:我使用以下语句成功导出到 excel:

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=C:\template.xls;', 
'SELECT * FROM [SheetName$]') 
select * from myTable

Is there any standard way to use this template specifying a new name for the excel sheet so that the template never gets written to or do I have to come up with some work-around?是否有任何标准方法可以使用此模板为 Excel 工作表指定一个新名称,以便模板永远不会被写入,或者我是否必须想出一些解决方法?

What's the best way to do this in people experience?在人们的体验中,做到这一点的最佳方式是什么?

You'd have to use dynamic SQL.您必须使用动态 SQL。 OPENROWSET etc only allows literals as parameters. OPENROWSET等只允许文字作为参数。

DECLARE @myfile varchar(800)

SET @myfile = 'C:\template.xls'

EXEC ('
insert into OPENROWSET(''Microsoft.Jet.OLEDB.4.0'', 
''Excel 8.0;Database=' + @myfile + ';'', 
''SELECT * FROM [SheetName$]'') 
select * from myTable
')

Remember: the path is relative to where SQL Server is running请记住:路径是相对于 SQL Server 运行的位置

您不能先复制模板,然后将副本的文件名传递到 OPENROWSET 中吗?

You can use a template in one location and the data file in other location.您可以在一个位置使用模板,在其他位置使用数据文件。 When you run the script , it will delete the old file and generates a new data file.当您运行该脚本时,它将删除旧文件并生成一个新数据文件。

 EXEC xp_cmdshell 'del D:\template.xls'
 EXEC xp_cmdshell 'copy C:\template.xls D:\template.xls'

 INSERT INTO OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
 'Excel 8.0;Database=D:\template.xls;', 
 'SELECT * FROM [SheetName$]') 
  SELECT * FROM myTable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM