简体   繁体   中英

Export SQL Server query to CSV using script

Let say I have 1 query for remote SQL Server:

SELECT * FROM USER

And I would like to export using any kind of script without using manual intervention from SSMS. I expect the output to be like this:

id,username,firstName,lastName
1,amy,Amy,NULL
2,bob,Bob,Marley
3,cat,Cathy,NULL

How can I export into something like above?


I noticed there are few old discussions on this with variety of custom workaround that doesn't work for me. I prefer the exported file contains header, NULL value and without start/end quotes. Here's my closest script to achieve the result:

bcp "SELECT * FROM USER;" queryout export.csv -S 'localhost' -U sa -P 'password' -d 'mydatabase' -c -t  ',' 

Current output:

1,amy,Amy,
2,bob,Bob,Marley
3,cat,Cathy,

You can use SQLCMD to achieve that like below:

EXEC master..xp_cmdshell 'SQLCMD -E -W -Q "SET NOCOUNT ON SELECT * FROM dbname.schemaname.USER" -s "," | findstr /V /C:"-" /B > E:\export.csv'

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