SQL Append Write To File

jstevens
GoldLounger
Posts: 2628
Joined: 26 Jan 2010, 16:31
Location: Southern California

SQL Append Write To File

Post by jstevens »

I would like to append data written to a file using the code below. The code works fine but overwrites the file each time.

I know using ">>" in a DOS command one can append data to a file.

Code: Select all

DECLARE @ExportSQL nvarchar(max); SET @ExportSQL = N'EXEC master.dbo.xp_cmdshell ''bcp "SELECT * FROM MyDatabase.dbo.MyTable WHERE FileName = ''''' + @FileName + '''''" queryout "' + @OutputFilePath + '\OutputData.csv" -T -c -t, -S ServerName'''

EXEC(@ExportSQL)
Regards,
John

User avatar
HansV
Administrator
Posts: 78412
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: SQL Append Write To File

Post by HansV »

I don't think that's possible, You could import the csv file, append the new records to the imported table, and then export that.
Best wishes,
Hans

jstevens
GoldLounger
Posts: 2628
Joined: 26 Jan 2010, 16:31
Location: Southern California

Re: SQL Append Write To File

Post by jstevens »

Hans,

Based on your suggestion I ended up with code that inserts the records into a temptable and as a final step writes to a csv file.

Thanks for the push in the right direction.
Regards,
John