exec xp_cmdshell bcp syntax

VK_217 picture VK_217 · Aug 16, 2017 · Viewed 9.4k times · Source

I can't seem to find the right syntax to export data with column names using exec xp_cmdshell bcp in sql server management studio.I've tried the below variations

EXEC xp_cmdshell bcp "select "a_id","b_id","c_id" union select a_id,b_id,c_id from  tablename out 
"\\network_path\a.txt" -c -Uusername -Ppassword -Sservername"

And

EXEC xp_cmdshell bcp 'select 'a_id','b_id','c_id' union select a_id,b_id,c_id from  tablename out 
'\\network_path\a.txt' -c -Uusername -Ppassword -Sservername'

And

EXEC xp_cmdshell bcp 'select "a_id","b_id","c_id" union select a_id,b_id,c_id from  tablename out 
"\\network_path\a.txt" -c -Uusername -Ppassword -Sservername'

And

EXEC xp_cmdshell bcp "select 'a_id','b_id','c_id' union select a_id,b_id,c_id from  tablename out 
'\\network_path\a.txt' -c -Uusername -Ppassword -Sservername"

I have successfully used the below command to export the table,however I also need the column names.

bcp tablename out "\\network_path\a_test.txt" -c -Uusername -Ppassword -Sservername'

Answer

Element Zero picture Element Zero · Aug 16, 2017

Ok you'll actually need to order the header row so it appears on top. This should handle it

EXEC xp_cmdshell 'bcp "select * from (select ''a_id'' as a_id,''b_id'' as b_id,''c_id'' as c_id union select a_id,b_id,c_id from tablename)q order by case a_id when ''a_id'' then 0 ELSE 1 END" queryout "\\networkpath\a.txt" -c -Uusername -Ppassword -Sservername -ddatabasename'