SQL results to CSV file with column headers
-
Thursday, February 07, 2013 3:43 PM
Hi
I am exporting SQL results into CSV file using BCP, I need to include column headers for the report. Any help is appreciated.
Below is my code
set @sql = 'bcp "select * from Sam.dbo.Samtmp" queryout '+@SAMLog_file_location+' -c -T -S' + convert(varchar,@@servername);
exec master..xp_cmdshell @sql
All Replies
-
Thursday, February 07, 2013 4:20 PM
Please check the following threads for a solution to your issue.
Hima, To help the community better identify relevant thread, please don't forget to mark as answer or vote as helpful if and answer helps.
- Edited by Hima Nagisetty Thursday, February 07, 2013 4:20 PM
- Proposed As Answer by CountryStyle Thursday, February 07, 2013 4:32 PM
- Unproposed As Answer by CountryStyle Thursday, February 07, 2013 4:32 PM
- Proposed As Answer by CountryStyle Thursday, February 07, 2013 4:53 PM
- Unproposed As Answer by CountryStyle Thursday, February 07, 2013 4:53 PM
- Marked As Answer by Iric WenModerator Monday, February 18, 2013 6:47 AM
-
Thursday, February 07, 2013 5:01 PM
Hope this helps.
SELECT 'COLUMNNAME1' AS COLUMNNAME1, 'COLUMNNAME2' AS COLUMNNAME2 ... UNION ALL SELECT * FROM MYTABLE
http://www.sqlservercentral.com/Forums/Topic1036089-146-1.aspx
Thanks & Regards,
Prasanna Vaitheswaran
Please mark the post as 'Answer', if it addresses or resolves your query. Please click on 'Vote as Helpful', if it is helpful. -
Thursday, February 07, 2013 5:08 PM
Hello Naveen,
This is a regular problem and you're not alone. The solution I found was to actually create a table to output first (you can always truncate it if you're wanting to use it dynamically). Into this table insert the column headers first, then append your data into it.
When you execute BCP it should output the column headers with it, unfortunately there's no easy way of being able to do this other than "tricking" SQL into performing the task for you.
Regards,
Johnny
-
Thursday, February 07, 2013 5:58 PMSSIS can do this for you pretty easily. Just mark the 'Column Names in the first data row' checkbox in the Flat File Destination.
-
Thursday, February 07, 2013 8:04 PMThanks Hima

