Social media is evolving at a rapid pace and every day I keep on getting question from different methods. Here is the latest question which I received on my Facebook page. The question was how to export the data of query into CSV using SQLCMD.
This is indeed very easy process and very simple command to export any query data. For example we will use AdventureWorks2012 database. Here is the query we will be using for our demonstration.
SELECT TOP 10 sp.BusinessEntityID,
FROM Sales.SalesPerson sp
The above query will return following result set.
Now we can export above data to CSV using SQLCMD using following command.
SQLCMD -S . -d AdventureWorks2012 -Q “SELECT TOP 10 sp.BusinessEntityID, sp.TerritoryID, sp.SalesQuota, sp.Bonus, sp.CommissionPct FROM Sales.SalesPerson sp” -s “,” -o “e:\result.csv”
Generically you can use the following syntax:
SQLCMD -S YourSQLServer -d YourDatabase -U YourUserName -P YourPassword -Q “Your Query” -s “,” -o “C:\Yourfilename.csv”
Now you can go to your file location and open the file and you will see that new csv file created there. When you open the csv file you will notice the results of the query.
Watch the video on the same subject:
Reference: Pinal Dave (http://blog.sqlauthority.com)