问题
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