Export Data as csv file from SQL server using command line tools

In the post we will be discussing about the ways of exporting data from SQL server to csv file. As per the use case the output should have:

  1. Header row
  2. The seperator of columns should be ",".
  3. The file should be encoded as UTF-8.

There are two tools for exporting data from SQL Server to csv file. These are sqlcmd and bcp.

SQLCMD

The command which can be used for this purpose is
Sqlcmd -S "<ServerName\InstanceName>" -d "<DatabaseName>" -U "<UserName>" -P "<Password>" -i "<SQLScriptFilePath>" -W -f 65001 -h -1 -s "," -o "<OutputFilePath>"

E.g.: Sqlcmd -S "10.00.00.00" -d "EmployeeDatabase" -U "User1" -P "Password" -i "Script1.sql" -W -f 65001 -h -1 -s "," -o "c:\File.csv"

Attributes


  • -W is used to remove all the whitespaces
  • -h -1 is used to remove the header (if header is not removed from sqlcmd command than header will come in csv output but with "---" below the header line.
  • -f 65001 is used for specifying UTF8 encoding
  • -s is used to specify separator ","


Workarounds


  • We can use -Q "SELECT * from tbl_Employee" instead of -i "Script.sql"
  • The header should be included using SQL query. E.g. SELECT 'EmployeeID' AS EmployeeID, 'EmployeeName' AS EmployeeName UNION ALL SELECT EmployeeID,EmployeeName FROM tbl_Employee.
  • We can also use Windows authentication using -T attribute instead of specifying username and password.

BCP


The command which can be used for this purpose is
bcp "<storedprocedure or query>" queryout "<outputfile>" -S "<ServerName\InstanceName>" -d "<DatabaseName>" -U "<UserName>" -P "<Password>" -w -t"," -r"\n"

Attributes

  • -t specifies the field terminator.
  • -r specifies the row seperator


Comments

Popular posts from this blog

Query within a Task Scheduler Library folder using schtasks.exe and getting total number of tasks

Getting Started with AppCmd.exe