简体   繁体   中英

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

一个标准的众所周知的 hack 是选择列名 union all 使它们成为查询本身的一部分并导出它,像这样......

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

@M.Ali solution works perfectly. You could also use the below to include the columns more dynamically:

DECLARE @ColumnHeader varchar(8000)
SELECT @ColumnHeader =  COALESCE(@ColumnHeader+',' ,'')+ ''''+column_name +'''' 
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='tblA';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM