I have a SQLCMD below (it works fine) that I execute from command line to write SQL data to a .csv file. I was having an issue with commas that are inside database values (which ruins the csv separations) by casting the string field to an nvarchar(100) surrounded by escaped-double quotes, like this:
SQLCMD -s"," -S servername -U username -d databasename -W -o
"mydatafile.csv” -Q "SET NOCOUNT ON
SELECT Account,'""' + cast ([ColDescription] as nvarchar(100)) + '""' as ColumnDescription" FROM myTable
...the column with the escaped double-double quotes is ColDescription, and the original string field actually has 100 characters. So, this fixed my issue but now I am facing a new issue with my database values that start with quotes. For those records where the data value actually starts with quotes, I assume I would have wanted to escape with 3 instances of double-quotes (so that the result string will have all double-quotes escaped).
But, how can I tell SQL to escape any number of instances of double-quotes? I don't know which records will have double-quotes, or 2 double-quotes, or what.
Better yet, I would ideally like to display the double-quotes in my .csv file if they existed in the data. So maybe escaping them altogether isn't what I need. I'm not sure that I'm researching the right words for this problem either. I think I want to escape a pattern of characters...does this sound like a REGEX thing? I haven't used REGEX in sql before and my instinct tells me that's too complicated for an issue that seems common and must have been solved before.
EDIT: I also tried a new approach as I made a comment about below. I changed my SQLCMD to the following (although this is a stripped-down version of my "real" query). But notice I used the Replace function to replace all quotes with 2 quotes. I thought that by making an even number of quotes, all of them will be escaped in the .csv export.
SQLCMD -s"," -S servername -U username -d databasename -W -o
"mydatafile.csv” -Q "SET NOCOUNT ON
SELECT Account,'""' + Replace(cast ([ColDescription] as
nvarchar(100)),'"','""') + '""' as ColumnDescription" FROM myTable
...But now my error in the command prompt is "Unexpected Argument." I think "Replace" is a keyword that maybe I would also need to escape in windows...? The new Select statement works fine directly in SQL, though. I just can't execute the command anymore.