Search code examples
sqlsql-serverexport-to-csvbcp

Switch to include column headers in bcp


I don't see in the documentation how to include column headers with in my csv-type output file. I'm sure this is a duplicate, But I can't seem to find one that leads to my exact need.

Here's my command:

 bcp "select * from MYDB.dbo.MyTable" queryout "C:\outputfile.csv" -c -t"," -r"\n" -S ServerName -T -k -E

Solution

  • A standard well known hack is to select the column names union all make them part of the query itself and export that, something like this......

    bcp "SELECT 'ColName1','ColName2','ColName3' UNION ALL select ColName1,ColName2,ColName3 from MYDB.dbo.MyTable" queryout "C:\outputfile.csv" -c -t"," -r"\n" -S ServerName -T -k -E