BCP exporting CSV data with single and double quotes?

135 Views Asked by At

This is the BCP that I currently run:

bcp.exe "select top 4* From MyTable " queryout output.csv -S MyServer -T -c -C RAW -t'\",\"' -r'\"\r\"' -q

It generates the CSV file, but every column has a single and a double-quote:

enter image description here

Are the parameters in the BCP incorrect?

1

There are 1 best solutions below

0
jamie On

Parameter is not correct for the -t and -r parameter. For these parameters you would use the doublequote character to enclose the text of your delimiter. Normally, if your delimiter contains no special characters (special as in, meaningful to the BCP command... like a doublequote) you do not need to enclose your delimiter at all. So to set the field delimiter as a pipe character you would use:

-t, or you could use -t","

either of those would work. But since you want to include a doublequote in your delimiter, you (correctly) include the backslash escape character. All good so far...

Lastly, as I stated earlier, if you need to enclose your delimiter in quotes (lets say because there is a space in your delimiter and if you didn't put it in quotes BCP would think the space was the end of your delimiter) you need to use doublquote and not singlequote.

Your use of single quote is not read by BCP as the beginning of an quote-enclosed delimiter... it's been read as PART of the delimiter.

All you need is this to get doublequotes and commas:

-t\",\"

that's it, no singlequotes needed. there is no whitespace in your delimiter to trick BCP into thinking the delimiter is done before it really is.

NOTE - you're going to have another issue with using BCP to delimit data in this manner. The first and last columns are going to be different.

The last column is easy, just need to make a slight different delimiter than all the "middle" ones. Can do that with the row terminator parameter (-r).

But the FIRST column is tricky. I suggest you lookup other questions here about add a quote/doublequote to the first column of BCP out data. It involves use of a BCP format file and a "dummy" column in that format file at the start.