Using the following sqlcmd script:
sqlcmd -S . -d MyDb -E -s, -W -Q \"select account,rptmonth, thename from theTable\"
> c:\\dataExport.csv
<
In addition, if you want to query out all records in a table, you can code as
Assign the above queries into a variable %query%. The the command will be looks like as below.
SQLCMD -h -1 -W -E -S %sql_server% -d %sql_dabase% -Q %query% -s"," -o output_file.csv
Solutions:
1) To remove the row count ("(139 rows affected)") you should use SET NOCOUNT ON
statement. See ref.
2) To remove column headers you should use -h
parameter with value -1
. See ref (section Formatting Options).
Examples:
C:\Users\sqlservr.exe>sqlcmd -S(local)\SQL2012 -d Test -E -h -1 -s, -W -Q "set nocount on; select * from dbo.Account" > d:\export.txt.
or
C:\Users\sqlservr.exe>sqlcmd -S(local)\SQL2012 -d Test -E -h -1 -s, -W -Q "set nocount on; select * from dbo.Account" -o "d:\export2.txt"