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

后端 未结 11 1802
天涯浪人
天涯浪人 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:30

    sqlcmd -S myServer -d myDB -E -o "MyData.txt" ^
        -Q "select bar from foo" ^
        -W -w 999 -s","
    

    The last line contains CSV-specific options.

    • -W   remove trailing spaces from each individual field
    • -s","   sets the column seperator to the comma (,)
    • -w 999   sets the row width to 999 chars

    scottm's answer is very close to what I use, but I find the -W to be a really nice addition: I needn't trim whitespace when I consume the CSV elsewhere.

    Also see the MSDN sqlcmd reference. It puts the /? option's output to shame.

提交回复
热议问题