Share via


SQL: Handling comma while creating CSV

If you are facing issues because of ',' (comma or .csv file) in the data of your text column, you can use the '|' sign.

EXECUTE master.dbo.xp_cmdshell 'bcp "SELECT Column1, Column2, Column3 FROM YourDB.[dbo].[YourTable] ORDER BY 1" queryout E:\Objects3.txt -t"|" -c -T '

If you still want to use the comma as separator due to any limitation, you can use char(34) before and after the column that you think may have a comma in the text. Adding char(34) i.e. double quote, will treat the text with comma as a single value.

EXECUTE master.dbo.xp_cmdshell 'bcp "SELECT Column1, char(34) + Column2 + char(34) , Column3 FROM YourDB.[dbo].[YourTable] ORDER BY 1" queryout E:\Objects3.txt -t"," -c -T '

The above code assumes that you have comma in Column 2 and the file created is comma separated CSV.