views:

2104

answers:

2

All,

I am successfully exporting to excel with the following statement:

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?

What's the best way to do this in people experience?

+1  A: 

YOu'd have to use dynamic SQL. OPENROWSET etc only allow literals as paramters.

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

gbn
this is good - but I'd still have to put the template there in the first place so I cannot come up with names in the SQL, I'd have to programmatically create the spreadsheet first.
JohnIdol
Ah I get you. No, you can't manipulate Excel that way in T-SQL. Perhaps a CLR stored proc?
gbn
never worked with CLR SPs - but I guess it's easy enough - any good sample to get me going?
JohnIdol
Sorry... not used them. The "SQLCLR" tag has 31 related questions.
gbn
I'll clarify.. our corporate build from DB engineering says no
gbn
A: 

Couldn't you make a copy of your template first, then pass the copy's filename into OPENROWSET?

Seth Ladd