


set @sql = 'select * from [server].dbname.dbo.tablename' set @bcp = 'bcp "' + @sql + '" queryout serverpathFileName.csv -T -t, -c' exec master..xp_cmdshell @bcp-t, references comma separated values Depending on the version of the BCP utility you may or may not be able to use temp tables.


I would use powershell to run your query.
$results = Invoke-sqlcmd -serverinstance "instancename" -database "dbname" -query "query"$results | export-csv filename -force
That should get you want you want. Just be sure that you have SQL Server 2008 client tools installed and that you are adding the ps snappin in order to use the invoke-sqlcmd cmdlet.
Use the sp_CreateDelimitedTextFile command. Was very easy:
EXEC
sp_CreateDelimitedTextFile 'name of view I created', 'Full path to .csv file'And that was it.
Actually, let me elaborate that I put the command inside a procedure that is called when I want to build the file.