Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a csv file using select query in SQL [duplicate]

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?

like image 557
whiterose Avatar asked Jul 21 '11 13:07

whiterose


People also ask

How do I export SQL query results to Excel automatically?

Go to "Object Explorer", find the server database you want to export to Excel. Right-click on it and choose "Tasks" > "Export Data" to export table data in SQL. Then, the SQL Server Import and Export Wizard welcome window pop up.


2 Answers

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

like image 168
Rahul Avatar answered Oct 02 '22 16:10

Rahul


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.

like image 45
Yuck Avatar answered Oct 02 '22 15:10

Yuck