1

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,
1
  • What is the issue with your current bcp script ? Commented Feb 14, 2020 at 2:46

1 Answer 1

2

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'
Sign up to request clarification or add additional context in comments.

1 Comment

i have modified your command to suits my need SQLCMD -b -S %DB_SERVER% -d %DB_NAME% -W -i %NOCOUNTSQL_FILEPATH%,%FILEPATH% -s "," -r0 | findstr /V /C:"-" /B > %EXPORT_FILENAME%

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.