SQL 服务器批量插入跳过主键冲突

SQL Server Bulk Insert Skip Primary Key Violations

我目前正在使用 SQL 服务器的本机 Bulk Insert 过程将多个表从文本文件加载到数据库中。

这一直运行良好,甚至可以优雅地处理截断、空和格式错误。如果任何列太大,不应该为空,或者如果根据格式文件找到的列数不正确,这些行将被跳过并转发到错误文件。

但是最近,我的一个文本文件中输入了一个重复的主键。这导致批量插入简单地失败,没有行被转发到错误文件。

目前我的批量插入命令如下所示:

BULK INSERT table.table FROM 'data_file.txt' WITH(
    BATCHSIZE = 100000,
    CODEPAGE = 1252,
    DATAFILETYPE = 'char',
    FIRSTROW = 2,
    KEEPNULLS,
    MAXERRORS = 1000000000,
    TABLOCK,
    FORMATFILE = 'format_file.txt',
    ERRORFILE = 'error_file.txt'
)

有没有一种方法可以使用批量插入来像处理其他错误一样处理主键违规?理想情况下,我希望将包含 PK 违规的行转发到同一个错误文件。

要直接回答你的问题,

UNIQUE, and PRIMARY KEY constraints are always enforced. When importing into a character column that is defined with a NOT NULL constraint, BULK INSERT inserts a blank string when there is no value in the text file.

我建议为您的批量插入使用分段或临时 table 并将其从那里移动到实际的 tables。

没有 CHECK_CONSTRAINTS 选项的

BULK INSERT 也会对您的 table:

产生其他影响

CHECK_CONSTRAINTS

Specifies that all constraints on the target table or view must be checked during the bulk-import operation. Without the CHECK_CONSTRAINTS option, any CHECK and FOREIGN KEY constraints are ignored, and after the operation, the constraint on the table is marked as not-trusted.

哪个可以negatively impact performance of queries if you don't fix it之后。