How to export data as CSV format from SQL Server using sqlcmd?

后端 未结 11 1765
天涯浪人
天涯浪人 2020-11-22 13:06

I can quite easily dump data into a text file such as:

sqlcmd -S myServer -d myDB -E -Q \"select col1, col2, col3 from SomeTable\" 
     -o \"MyData.txt\"
         


        
11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 13:32

    A note for anyone looking to do this but also have the column headers, this is the solution that I used an a batch file:

    sqlcmd -S servername -U username -P password -d database -Q "set nocount on; set ansi_warnings off; sql query here;" -o output.tmp -s "," -W
    type output.tmp | findstr /V \-\,\- > output.csv
    del output.tmp
    

    This outputs the initial results (including the ----,---- separators between the headers and data) into a temp file, then removes that line by filtering it out through findstr. Note that it's not perfect since it's filtering out -,-—it won't work if there's only one column in the output, and it will also filter out legitimate lines that contain that string.

提交回复
热议问题