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

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

    Is this not bcp was meant for?

    bcp "select col1, col2, col3 from database.schema.SomeTable" queryout  "c:\MyData.txt"  -c -t"," -r"\n" -S ServerName -T
    

    Run this from your command line to check the syntax.

    bcp /?
    

    For example:

    usage: bcp {dbtable | query} {in | out | queryout | format} datafile
      [-m maxerrors]            [-f formatfile]          [-e errfile]
      [-F firstrow]             [-L lastrow]             [-b batchsize]
      [-n native type]          [-c character type]      [-w wide character type]
      [-N keep non-text native] [-V file format version] [-q quoted identifier]
      [-C code page specifier]  [-t field terminator]    [-r row terminator]
      [-i inputfile]            [-o outfile]             [-a packetsize]
      [-S server name]          [-U username]            [-P password]
      [-T trusted connection]   [-v version]             [-R regional enable]
      [-k keep null values]     [-E keep identity values]
      [-h "load hints"]         [-x generate xml format file]
      [-d database name]
    

    Please, note that bcp can not output column headers.

    See: bcp Utility docs page.

    Example from the above page:

    bcp.exe MyTable out "D:\data.csv" -T -c -C 65001 -t , ...
    

提交回复
热议问题