首页 > 解决方案 > Postgres 在 SQL Server BCP 文件的最后一个预期列之后复制错误额外数据

问题描述

我正在将数据库从 Windows 上托管的 SQL Server 2016 迁移到 Debian 上托管的 Postgres 11。

我正在使用 SQL Server 2016 中的 BCP 实用程序导出数据,并使用 COPY 命令将其导入 Postgres 11。

对于很多表它都有效,但对于某些表,即使我的文件包含相同数量的列,我也会不断收到“最后一个预期列之后的额外数据”错误。COPY 命令似乎对包含空字符串的行有问题,在 Notepad++ 中显示为“NUL”。

这是我在 SQL Server 中的表的定义。(表名和列名已更改)

Create table test (
    TypeId  int not null,
    Name    nvarchar(50) not null,
    License nvarchar(50) not null,
    LastChanged timestamp not null,
    Id1 uniqueidentifier not null,
    Id2 uniqueidentifier not null,
    DescriptionCol  nvarchar(256) not null default '',
    ConditionCol    bit not null default 0,
    ConditionCol2   bit not null default 0,
    ConditionCol3   bit not null default 1,
    DescriptionCol2 nvarchar (2) not null default ''
)

这是 Postgres 中的表定义。

CREATE TABLE test (
    typeid integer NOT NULL,
    name citext COLLATE pg_catalog."default" NOT NULL,
    license citext COLLATE pg_catalog."default" NOT NULL,
    lastchanged bytea NOT NULL,
    id1 uuid NOT NULL,
    id2 uuid NOT NULL DEFAULT uuid_generate_v4(),
    descriptioncol text COLLATE pg_catalog."default" NOT NULL DEFAULT ''::text,
    conditioncol boolean NOT NULL DEFAULT false,
    conditioncol2 boolean NOT NULL DEFAULT false,
    conditioncol3 boolean NOT NULL DEFAULT true,
    descriptioncol2 text COLLATE pg_catalog."default" NOT NULL
)

我以这种方式提取数据:

bcp Database.Schema.test out E:\MyFile.dat -S ServerName -U User -P Password -a65535 -c -C 65001

然后我连接到远程 Postgres 服务器并以这种方式导入数据:

\copy Schema.test FROM 'E:\MyFile.dat' (DELIMITER E'\t', FORMAT CSV, NULL '', ENCODING 'UTF8');`

现在,如果我打开在 Notepad++ 中生成的文件,我会看到“NUL”字符,这似乎是 COPY 命令无法解决的问题。

记事本中的文件

如果我尝试将一些数据放在第一行的“NUL”字符中,那么复制命令会在第三行而不是第一行上为我提供“最后一个预期列之后的额外数据”。我无法编辑文件并用其他内容替换“NUL”字符,因为我有数百个表要迁移到一些非常大的表。

我需要为 SQL Server BCP 实用程序或 Postgres COPY 命令指定一个选项才能使其工作。

标签: sqlsql-serverpostgresqldatabase-migrationcsv-import

解决方案


正如@Tometzky所说,

bcp 实用程序将空字符串表示为空字符串,将空字符串表示为空字符串。

这解释了不良行为的原因。

作为的替代方案,您可以考虑以这种方式使用 (Microsoft SQL Server Integration Services)。它易于使用,并且在 DBMS 系统之间具有广泛的兼容性。


推荐阅读