I want to export a SQL table to a CSV file automatically within a query. I've already accomplished to export a SQL table to a .CSV but the output was a TAB-separated file and without the column headers. How to make the output comma separated and with column headers?
See below the query that works but without the comma delimiter and column headers.
DECLARE @cmd NVARCHAR(4000)
DECLARE @pathAndFileName NVARCHAR(MAX)
DECLARE @result INT
SET @pathAndFileName = 'C:\test.csv'
SET @cmd = 'bcp " SELECT * from testdb.dbo.test_table " queryout "'
+ @pathAndFileName + '" -w -T -t -S Servername\SQLExpress; '
EXEC @result = xp_cmdshell @cmd
SELECT @result