MSSQL – How To Output To A File

There is a very, very simple one liner within MySQL to dump the results of a query into a text file. Nothing so simple exists within MSSQL, but there are fairly easy workarounds. Using BCP, one can use the xp_cmdshell to pass the results into the desired file.

use DatabaseName
go

declare @FileName varchar(50)
declare @bcpCommand varchar(2000)

set @FileName = REPLACE(‘c:\temp\bcp\postcodes_’+CONVERT(char(8),GETDATE(),1)+’.csv’,'/’,'-’)

set @bcpCommand = ‘bcp “select left(postcode,4), count(*) from DatabaseName..TableName where customersequence = 0 group by left(postcode,4) order by count(*) desc” queryout “‘
set @bcpCommand = @bcpCommand + @FileName + ‘” -U username -P password -c’

EXEC master..xp_cmdshell @bcpCommand

This dumps a load of postcode information, based on usage, into a csv file in c:\temp\bcp. What the query is doesn’t really matter, just the bcp commands to provide us with the results in a file of our choosing (.csv in this case).

The @FileName command simply appends the current date to the file in order to keep track of queries.

Leave a Reply