views:

953

answers:

2

How to save query result using T-SQL in a csv file in SSMS 2008? Needs to be done programmatically.

+1  A: 

You could use System.Diagnostics.Process to run the SQLCMD or OSQL or BCP programs to dump out csv files.

Preet Sangha
Agree BCP is simplest way; this is a good primer http://www.simple-talk.com/sql/database-administration/creating-csv-files-using-bcp-and-stored-procedures/If BCP isnt an option then a CLR function would let you do it too.
u07ch
osql and bcp can't be run from the query window as these are command line programs. sqlcmd could work if you have access to it.
Tony_Henrich
A: 

Here is an example I found from google. Play around with the parameters.

EXEC master..xp_cmdshell 'sqlcmd -X -S server -q "SET NOCOUNT ON Select 'department','FundCode','Month' SELECT * FROM pubs.dbo.test" -s , -w 255 -u -o "\\server\output.csv" -h-1'
jdelator