使用带有双引号的bcp实用程序导出数据

时间:2019-05-18 10:33:10

标签: sql-server regex shell bcp

我正在尝试使用 bcp实用工具命令行从MS sql服务器导出数据。问题在于,在导出的输出中,第一行缺少第一个双引号,我无法解释原因。

在我用于导出的命令下面:

 /opt/mssql-tools/bin/bcp db_schema out dump.csv -c -t"\",\"" -r"\"\n\"" -S my_host -U my_user

但是输出结果缺少导出的csv文件第一行(仅第一行)的第一双引号:

801","40116","Hazelnut MT -L","Thursday Promo","Large","","5.9000","","801","1.0000","","3.6500","2.2500",".0000","default","","","","","Chatime","02/06/2014","09125a9cfffd4143a00e73e3b62f15f2","CB01","",".0000","5.9000","6.9000",".0000",".0000",".0000",".0000",".0000",".0000","0","","0","0","0","","","","","","","","","Modern Milk Tea","","","0","","","1","0","","","","","","","","0","Hau Chan","","","","","","","","","","0","","","","","","","-1","","","","","","","","","","","","0","00000000420714AA","2014-06-02","1900-01-01","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""

我想念什么吗?

3 个答案:

答案 0 :(得分:1)

如果您知道字段名称,则可以尝试以下操作:

Create Table [names]
(
Id Int,
fname VarChar(15),
lname VarChar(25)
)
Insert Into names Values
(1, 'Jim', 'Morrison'),
(2,'Robert', 'Plant'),
(3,'Janis', 'Joplin')

BCP命令:将quotename()与char(34)一起使用

(此BCP命令使用受信任的连接)

bcp "SELECT quotename(Cast(Id As VarChar(15)),char(34)), quotename(fname,char(34)), quotename(lname,char(34)) FROM names" queryout dump.csv -c -t"," -S SERVER -d DBNAME -T

结果:

"1","Jim","Morrison"
"2","Robert","Plant"
"3","Janis","Joplin"

答案 1 :(得分:0)

我敢打赌,您在文件末尾也有一行,只是单引号引起来。为什么?使用您提供的命令行开关,您说的是“每个字段以","结尾,每行以"\n"结尾。这就是它的作用。

因此,第二行和后续行以双引号开头,因为前一行结尾。

Clippy DBA说:“您似乎正在尝试生成CSV”。不知道为什么,这对我来说很难。。。。具体来说,将要读取该文件的内容是什么?您将使用Excel或其他需要特定格式的内容阅读此书吗?将其导入到另一个数据库表中吗?

答案 2 :(得分:0)

level3looper提供的quotename答案适用于您的情况。

出于完整性考虑,我提供了我过去为相同目的提供的解决方案。 我比较喜欢这一点,因为它将格式的定义保留在格式文件中,这是我更喜欢去的地方。 quotename是快速,临时工作的好解决方案,但是对于自动化,业务流程,我建议您使用下面的链接。

基本上,您只需在提取文件的定义的开头添加一个“虚拟”列,并用单引号将该列定界。然后,您还要在格式文件中记下以跳过第一列。这只是在行首加上双引号。

sql server bcp bulk insert pipe delimited with text qualifier format file