Custom column name for bcp queryout SQL Server

被刻印的时光 ゝ 提交于 2019-12-25 09:29:43

问题


I want to rename the column name in the select clause of a bcp queryout command.I've tried the below variations and none of them work.I want to rename the first and third column to email_address and id respectively.

I am calling the bcp command in a batch script.

bcp "select email as 'email_address', first_name, p_id  as 'id' from table_name" queryout 15Days.txt -c -Sservername -Uusername -Ppassword -t,
bcp "select email as [email_address], first_name, p_id  as [id] from table_name" queryout 15Days.txt -c -Sservername -Uusername -Ppassword -t,
bcp "select email 'email_address', first_name, p_id 'id' from table_name" queryout 15Days.txt -c -Sservername -Uusername -Ppassword -t,
bcp "select email email_address, first_name, p_id id from table_name" queryout 15Days.txt -c -Sservername -Uusername -Ppassword -t,

Can someone point me to towards the right solution?


回答1:


If you looked at the text files produced by bcp you'll notice column names are not exported. Only data is exported.

The link Alex posted describes a way to add the column names to the output.You are actually adding the fields as first data column to your data using UNION. I recommend against it, because it requires casting all fields as strings making for a complex query.

Step 1 Output the columns

I would output a text file with the desired column names to one text file. Lets call that file "columnnames.csv". You may even create a repository of fixed column name files if need be.

Step 2 Output the data

Use bcp to output the data as you did before. Lets call that output "data.csv"

Step 3 Combine the two files

You can use this simple batch command to combine the data

copy /b columnnames.csv+data.csv combined.csv

or

type columnnames.csv data.csv > combined.csv

Helpful resources

How to query against the schema to get the column names.



来源:https://stackoverflow.com/questions/45287612/custom-column-name-for-bcp-queryout-sql-server

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