Using SQLCMD to export SQL Server Data as Comma Seperated Values

I have doing a couple of posts on SQLCMD recently (here and here) and have received some interesting questions too. One of the questions that caught my attention was to export SQL Server Data as CSV’s using SQLCMD.

Here’s the query to so do:

sqlcmd -S Suprotim-PC -d Northwind -E -Q "SELECT CustomerID, CompanyName, ContactName from Customers" -o "D:\MyData.csv" -s","

This query extracts data from 3 columns from the Customers table of the Northwind database and saves it in D:\MyData.csv

After running the command, here’s the output received

image


About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

5 comments:

Unknown said...

There's an easier way to export a CSV with BCP. Or you could use a script like this one ! http://www.pollusbrodeur.com/wiki/ow.asp?CSV.BAT

Suprotim Agarwal said...

Thanks Pollus. I will check it out!

Dinesh Dattatray Vishe said...

Great If i want sqlcmd result in some sql table then ??
what to do ??
Pleasew help me...

Dinesh Dattatray Vishe said...

If i want sqlcmd query result in MSSQL table then what to do??
Please help me...

Unknown said...

If you need to push a query result in a MS SQL table, all you need to do is use either: SELECT...INTO or INSERT...FROM, depending if the destination table exists or not. Here's an example: SQLCMD -Q "SELECT * INTO TableResult FROM MyTable"