【问题标题】:SQL Bulk Insert Foreign Key ConflictSQL 批量插入外键冲突
【发布时间】:2016-10-17 19:07:13
【问题描述】:

我在运行 CSV SQL 批量插入时遇到错误。我收到以下错误消息:

(25000 row(s) affected)
Msg 547, Level 16, State 0, Line 13
The INSERT statement conflicted with the FOREIGN KEY constraint "fk_Employee_Store". The conflict occurred in database "SkysDoggieDaycareDB", table "dbo.Store", column 'StoreID'.
The statement has been terminated.

(1000 row(s) affected)
Msg 547, Level 16, State 0, Line 13
The INSERT statement conflicted with the FOREIGN KEY constraint "fk_Employee_Service_Emp". The conflict occurred in database "SkysDoggieDaycareDB", table "dbo.Employee", column 'EmployeeID'.
The statement has been terminated.

StoreID 和 EmployeeID 字段是在这些插入语句之前在 Store 和 Employee 表中创建的。我不确定我做错了什么。有什么想法吗?

【问题讨论】:

  • 使用导入向导将 csv 文件导入临时表。然后将 ID 与父表进行比较以查看是否缺少任何 ID。

标签: sql-server foreign-keys bulkinsert


【解决方案1】:

也许您正试图在插入父表之前将数据插入子表。

【讨论】:

    【解决方案2】:

    当您必须批量加载一组通过外键约束相关的表时,您必须尝试确保首先插入所有父行,然后是子行(将 FK 约束返回给父行)。

    有时没有办法让插入的顺序正确。在这种情况下,您应该删除 FK 约束,直到所有行都加载完毕,然后再恢复它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      相关资源
      最近更新 更多