SQL – Output Data from SQL Server To File – BCP

The following BCP command selects data from a table called CUSTOMERS in the DATA database and exports it to a file called FOO_REPORT.CSV:

@bcpcommand           varchar(1000)


SET @bcpcommand = ‘bcp “SELECT id, title, forename, surname, product FROM DATA.dbo.customers where product = ”FOO”” queryout C:\reports\FOO_REPORT.CSV -c -T”‘

EXEC master..xp_cmdshell @bcpcommand

 You can also output to .XLS and .TXT.