问题
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'
回答1:
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'
来源:https://stackoverflow.com/questions/45721214/exec-xp-cmdshell-bcp-syntax