January 24, 2010

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


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

5 Responses to "Using SQLCMD to export SQL Server Data as Comma Seperated Values"
  1. Pollus said...
    January 25, 2010 at 10:23 AM

    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

  2. Suprotim Agarwal said...
    January 26, 2010 at 12:03 AM

    Thanks Pollus. I will check it out!

  3. Dinesh Vishe said...
    July 9, 2012 at 12:49 AM

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

  4. Dinesh Vishe said...
    July 9, 2012 at 12:50 AM

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

  5. Pollus Brodeur said...
    July 9, 2012 at 8:07 AM

    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"

 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions