11

Possible Duplicate:
How to export data as CSV format from SQL Server using sqlcmd?

I want to generate CSV file using select query in SQL-server.

The code below is working correctly in mySQL:

select * into outfile 'd:/report.csv' fields terminated by ',' from tableName;

It generated the CSV file.

Does anybody know how can I create a CSV file using select query in SQL-server?

Community
  • 1
  • 1
whiterose
  • 4,391
  • 8
  • 24
  • 18
  • There is a SSMS 2008 addin tool that does this for your tables that can be customized by where and order by clauses. http://store.nmally.com/software/sql-server-management-studio-addons/ssms-addin-scripting-tool-insert-to-t-sql.html –  Jul 14 '13 at 06:33

2 Answers2

15

Will this do the work

sqlcmd -S server -U loginid -P password -d DBname -Q "select * from tablename" -o output.csv

EDIT:

Use -i options if you want to execute a SQL script like -i sql_script_filename.sql

Rahul
  • 76,197
  • 13
  • 71
  • 125
1
SQLCMD -S MyInstance -E -d sales -i query_file.sql -o output_file.csv -s

You can use OPENROWSET() to read from a CSV file within a T-SQL query but AFAIK you can't write to one. This is really what SSIS/DTS is for.

If you're working with it interactively in SQL Server Management Studio you could export a grid to a file.

anon
  • 4,163
  • 3
  • 29
  • 26
Yuck
  • 49,664
  • 13
  • 105
  • 135