I'm looking for a way to batch Export a SQL Server table to a csv file.
There are some solutions using sqlcmd or bcp, but so far I found none which properly escapes quotes, commas or line-breaks.
For example this command creates a nice csv but does ignore quotes and commas which renders the csv file unusable:
bcp MyDatabase..MyTable out c:\test.csv -c -T -t, -r\n -S MYPC
From my sample data of four rows each containing some other special character this would create a file like this:
1,contains " quote
2,contains , comma
3,contains ; semi
4,contains ' single quote
Due to the quotes and the comma this is not importable by other programs. Of course I could change the separator to tab or the pipe symbol, but this does not fix the real problem: Whatever the separator is, if it exists in the data it will render the export file unusable.
So how do I bulk export data in a batch to a working csv file using standard SQL tools like BCP, sqlcmd or similar?