关于如何在BCP和Bulk Insert中使用 文本限定符 |
如果你使用SQL Server的导入导出工具,你会在选择格式的时候有一个 文本限定符的选项,选择使用“ 或者‘ 把文本的内容引起来,但是在BCP和Bulk Insert中就找不到类似的参数和选项;
这次数据同步中,由于不考虑使用SQL之间直接传送数据,所以使用了文本文件作为中转,直接使用了BCP.exe,但是其中有些乱码的内容,就出现了问题; 再次导入的时候就会丢失一部分数据。
但是使用SQL自己的导出工具wizard,导出的文本的内容会用”引起来,再次用同样的办法导入的时候,数据则不会丢失;
在网上搜了好多bcp+"text qualifier",发现有好多人问题,但是大部分还是使用了其它的办法来导出数据;最终还是找到一个解决办法:修改格式文件fmt,
如果先生成一个格式文件,大概会是下面样子:
7.0
9 1 SQLCHAR 0 11 "," 1 au_id "" 2 SQLCHAR 0 40 "," 2 au_lname "" 3 SQLCHAR 0 20 "," 3 au_fname "" 4 SQLCHAR 0 12 "," 4 phone "" 5 SQLCHAR 0 40 "," 5 address "" 6 SQLCHAR 0 20 "," 6 city "" 7 SQLCHAR 0 2 "," 7 state "" 8 SQLCHAR 0 5 "," 8 zip "" 9 SQLCHAR 0 1 "\r\n" 9 contract ""
但是如果要加上”,则需要改成这个样子:
8.0
9 1 SQLCHAR 0 11 ",\"" 1 au_id "" 2 SQLCHAR 0 40 "\",\"" 2 au_lname "" 3 SQLCHAR 0 20 "\",\"" 3 au_fname "" 4 SQLCHAR 0 12 "\",\"" 4 phone "" 5 SQLCHAR 0 40 "\",\"" 5 address "" 6 SQLCHAR 0 20 "\",\"" 6 city "" 7 SQLCHAR 0 2 "\",\"" 7 state "" 8 SQLCHAR 0 5 "\",\"" 8 zip "" 9 SQLCHAR 0 1 "\"\r\n" 9 contract ""
这样出来的结果,实际上是把,改成了\",\" ,其中\是作为转义符出现的;也就是在,号的左右都加了";但是注意第一列和其它的不同;结果是第一列没有使用“”引起。
如果你需要将第一列也使用“引起来的话,需要在你的数据前再增加一列 null firstquote, 内容为空,实际上在你真正的第一列前面增加一个前置的” ;具体的办法请参见下面的内容,我没有用到,所以也没有深入搞,大家可以参考一下:
You need to use a format file for this. Using the pubs..authors table as an example,
we'll bcp out of a view that looks like this: use pubs go create view authors_csv as select null first_quote, * from authors Note that we are including a dummy column called first_quote that just returns NULL. It's just a little trick to get the leading quote on the first column. The format file looks like this: 8.0
10
1 SQLCHAR 0 0 "\"" 1 first_quote ""
2 SQLCHAR 0 11 "\",\"" 2 au_id ""
3 SQLCHAR 0 40 "\",\"" 3 au_lname ""
4 SQLCHAR 0 20 "\",\"" 4 au_fname ""
5 SQLCHAR 0 12 "\",\"" 5 phone ""
6 SQLCHAR 0 40 "\",\"" 6 address ""
7 SQLCHAR 0 20 "\",\"" 7 city ""
8 SQLCHAR 0 2 "\",\"" 8 state ""
9 SQLCHAR 0 5 "\",\"" 9 zip ""
10 SQLCHAR 0 1 "\"\r\n" 10 contract ""
That dummy column is also in the format file to get the leading quote on au_id. Here's the command line: bcp pubs..authors_csv out authors_csv.dat -fauthors_csv.bcp -Slindaw\ml_tg -T If you only need to enclose some of the columns in quotes, you can remove the extraneous one from the format file. Another alternative is to create a view that concatenates the quotes to the column values. Linda |