exec xp_cmdshell bcp syntax

血红的双手。 提交于 2021-02-05 06:56:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!