Hi,
I am using below stored procedure to export data to excel with header. but it is not displaying the header . i believe this is because the max length of query can be 8000. but I have more than 250 columns so probably the length of query is breaking the code.
can someone please help here.
Thanks in advance.
ALTER procedure [dbo].[proc_generate_excel_with_columns] ( @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.csv' --Generate column names in the passed EXCEL file set @sql='bcp "select * from (select ' + @columns + ') as header" queryout E:\test.csv -c -t, -T -S ' + @@servername exec master..xp_cmdshell @sql --Generate data in the dummy file set @sql='bcp "select * from CustomerTable where ReservationDate>''1/1/2013''" queryout E:\data_file.csv -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) --EXEC proc_generate_excel_with_columns 'CustomerTable','E:\test.csv'