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:
There are two tools for exporting data from SQL Server to csv file. These are sqlcmd and bcp.
Sqlcmd -S "<ServerName\InstanceName>" -d "<DatabaseName>" -U "<UserName>" -P "<Password>" -i "<SQLScriptFilePath>" -W -f 65001 -h -1 -s "," -o "<OutputFilePath>"
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"
- Header row
- The seperator of columns should be ",".
- 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 isSqlcmd -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
Post a Comment