Skip to content Skip to sidebar Skip to footer

Sql Server Bcp: How To Put Quotes Around All Fields?

I have this BCP command: 'bcp DBName..vieter out c:\test003.txt -c -T /t'\',\'' -S SERVER' The output CSV I get does not put quotes around the field names, instead it puts it arou

Solution 1:

Setting the row terminator in addition to the field terminator should do the trick

'bcp DBName..vieter out c:\test003.txt -c -T-t"\",\""-r"\"\n\""-SSERVER'

This will likely work, but miss off the leading " for the first field of the first line, and perhaps the last field of the last line - I'm not sure, just guessing really, no server here!

or try using QUOTENAME to wrap text fields (you could also wrap numbers, but that isn't normally required.)

'bcp "SELECT id, age, QUOTENAME(name,'"') FROM DBName..vieter" queryout c:\test003.txt -c -T -t"," -S SERVER'

Solution 2:

You need to use CHAR(34) for the quote. This page has more details: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=153000

Solution 3:

Alternatively, if you are fine for Powershell based script, you can try with below code, which does automatic quoting.

Invoke-sqlcmd -ConnectionString "Server=SERVERNAME, `
3180;Database=DATABASENAME;Trusted_Connection=True;"  `
-Query "SET NOCOUNT ON;SELECT * FROM TABLENAME" -MaxCharLength 700 | `
Export-Csv -NoTypeInformation -path C:\temp\FileName.csv -Encoding UTF8

Solution 4:

Here are the list of commands i used .

BCP "DECLARE @colnames VARCHAR(max);SELECT @colnames = COALESCE(@colnames + ',', '') + column_name from databaseName.INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='tableName'; select @colnames;" queryout "C:\HeadersOnly.csv" -r"\n\""  -c -T -Uusername -Ppassword -SserverName

bcp databaseName.schema.tableName out "C:\EmployeeDatawithoutheaders.csv" -T -t"\",\"" -r"\"\n\"" -c -Uusername -Ppassword -SserverName

copy /b C:\HeadersOnly.csv+C:\EmployeeDatawithoutheaders.csv C:\EmployeeData.csv

del C:\HeadersOnly.csv

del C:\EmployeeDatawithoutheaders.csv

Solution 5:

I guess your goal was to clearly seperate field values by using an unique identifier so that import procedure doesn't have an issue.

I had same issue and found this workaroud useful: Using an unusual field terminator, for example | or even a string /#/ can be very unique and shouldn't mess with your string content. You also can HEX-Values (limited, see https://docs.microsoft.com/en-us/sql/tools/bcp-utility?view=sql-server-2017)

export

bcp DB.dbo.Table out /tmp/output2.csv -c -t "/#/" -U sa -P secret -S localhost

import

bcp TargetTable in /tmp/output2.csv -t "/#/" -k -U sa -P secret -S localhost -d DBNAME -c -b 50000 

Post a Comment for "Sql Server Bcp: How To Put Quotes Around All Fields?"