Exporting stored procedure result to excel with column name
I have attached the code for storing the stored procedure outp开发者_开发知识库ut to an Excel sheet..
but I have few issues, they are
(1) all the columns are displayed in the first column of the excel sheet..which I don't need, I need to show the report in diff columns.. how to do that..
(2) if I use inner join with the main, how can I get the column names of the other table
Can anyone please help me out to solve the above issues?
alter procedure proc_generate_excel_with_columns
(
@db_name varchar(100),
@schm_name varchar(100),
@table_name varchar(100),
@file_name varchar(100)
)
as
--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='bcp " select * from (select ' + @columns + ') as t" queryout
c:\test.xls -c -t, -T -S ' + @@servername
exec master..xp_cmdshell @sql
--Generate data in the dummy file
set @sql = 'bcp "select * from st..VEN_FULLREPORTMASTER
where entry_date = convert(varchar, getdate() - 3, 105) "
queryout c:\data_file.xls -c -t, -T -S' + @@servername
-- exec master..xp_cmdshell @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)
If using SSIS is an option this would be a trivial task to complete using a data flow task.
Can you use SSIS or do you need a pure tSQL solution?
精彩评论