Tuesday, March 5, 2013

Exporting Query Results to CSV using SQLCMD

In this post , I will explain how to export the query result set to CSV file using SQLCMD.
In my previous posts, I explained STUFF Function, LEN Function, UNICODE Function, LEFT Function, CHARINDEX Function, CHAR Function, ASCII Function, Simple script to backup all SQL Server databases, Table-Valued Parameters and some other articles related to SQL Server.

Here, I am going to explain exporting the query result to CSV using SQLCMD in SQL Server.

This is a very easy process and a very simple command to export query data. Syntax of this command is as shown below-
 
Syntax-  
SQLCMD -S SQLServerName -d DatabaseName -U UserName -P Password -Q “SQL Query” -s “,” -o “C:\FileName.csv”

For example, I have following select query which I will export to CSV file.
Select SubID, SubCode, SubName
from Subjects

The above query will return the following result-
Query Result

Now we can export the above result set data to CSV using SQLCMD using following command-
SQLCMD -S Manish\SQL2008R2 -d TestDatabase -U Pcare -P Che
tu@123 -Q "Select SubID, SubCode, SubName from Subjects" -s "," -o "D:\Test1.csv"

Now you can go to your file location and you will find the new created CSV file there. When you open the CSV file you will get the result of the query.
Query Result to CSV

2 comments:

  1. I really like your blog thanks for sharing nice information with us. Keep it up!

    ReplyDelete
  2. thanks for your appreciations....

    ReplyDelete

^ Scroll to Top