How to export SQL data to CSV file with headers using BCP
I created a simple Stored Procedure (SP) that queries a table and renames the column names, and I'm able to push those results out to a CSV file *with* those header names when done manually.
But when I try to export the results to a CSV file by running the same SP using xp_cmdshell with bcp, the header row (Col1, Col2, and Col3) does not appear in the resulting CSV file.
ORIGINAL TABLE:
ColumnName1-----ColumnName2-----ColumnName3
Joe Schmo Customer
Jane Doe Customer
Tim Tiny Musician
QUERY WITHIN SP:
SELECT ColumnName1 AS Col1, ColumnName2 AS Col2, ColumnName3 AS Col3
FROM TABLENAME
QUERY RESULT:
Col1-----Col2-----Col3 <<<<----- WHAT I WANT!
Joe Schmo Customer
Jane Doe Customer
Tiny Tim Musician
Here's the code I'm using within the job:
EXEC xp_cmdshell 'bcp "EXEC DATABASENAME.dbo.STOREDPROCEDURENAME" QUERYOUT "\\MYSERVERNAME\files\export.csv" -c -t, -T -S'
CSV FILE RESULT USING BCP:
Joe Schmo Customer
Jane Doe Customer
Tim Tiny Musician
As you can see the headers are missing. What am I doing wrong?
|