【问题标题】:The INSERT statement conflicted with the FOREIGN KEY constraint problemINSERT 语句与 FOREIGN KEY 约束问题冲突
【发布时间】:2019-07-04 10:49:36
【问题描述】:

我有下面的脚本,这给了我一个错误: “INSERT 语句与 FOREIGN KEY 约束“FK_dbo.PlanShiftAssignments_dbo.User_UserId”冲突。冲突发生在数据库“SWS”、表“dbo.User”、“Id”列中。 声明已终止。”

如您所见,在 WHERE 子句中,我检查 dbo.User 中是否存在 UserId。其他可能的错误原因是什么?

更新:我也想知道 select 语句中的哪一行导致错误。任何有关调试此查询的建议将不胜感激。我正在使用 MS SQL Server Management Studio。

CREATE TABLE [dbo].[PlanShiftAssignments] (
    [PlanShiftId] [uniqueidentifier] NOT NULL,
    [Status] [int] NOT NULL,
    [UserId] [int],
    CONSTRAINT [PK_dbo.PlanShiftAssignments] PRIMARY KEY ([PlanShiftId])
)
CREATE INDEX [IX_PlanShiftId] ON [dbo].[PlanShiftAssignments]([PlanShiftId])
CREATE INDEX [IX_UserId] ON [dbo].[PlanShiftAssignments]([UserId])
ALTER TABLE [dbo].[PlanShiftAssignments] ADD CONSTRAINT [FK_dbo.PlanShiftAssignments_dbo.PlanShifts_PlanShiftId] FOREIGN KEY ([PlanShiftId]) REFERENCES [dbo].[PlanShifts] ([Id])
ALTER TABLE [dbo].[PlanShiftAssignments] ADD CONSTRAINT [FK_dbo.PlanShiftAssignments_dbo.User_UserId] FOREIGN KEY ([UserId]) REFERENCES [dbo].[User] ([Id])
insert into dbo.PlanShiftAssignments
                    select ps.Id as PlanShiftId, ISNULL(ps.AssigneeId, psi.UserId) as UserId, ISNULL(psi.[Status], 1) as [Status] from dbo.PlanShifts ps
                    left join 
                    dbo.PlanShiftInvitations psi
                    on ps.Id = psi.PlanShiftId
                    where (psi.UserId is not null and psi.UserId IN (select Id from dbo.[User])) 
                    or (ps.AssigneeId is not null and ps.AssigneeId IN (select Id from dbo.[User]))

【问题讨论】:

  • 要调试,您可以执行不带where 子句的select 并为各种条件添加列,例如case when psi.UserId IN (select Id from dbo.[User]) then 1 else 0 end as UserIdInUsers.

标签: sql sql-server entity-framework tsql entity-framework-migrations


【解决方案1】:

确保您始终在每个 INSERT 语句中包含目标的列列表。

insert into dbo.PlanShiftAssignments (
    PlanShiftId,
    UserId,
    Status)
SELECT
    ps.Id as PlanShiftId, 
    ISNULL(ps.AssigneeId, psi.UserId) as UserId, 
    ISNULL(psi.[Status], 1) as [Status]
...

您的表是按照PlanShiftId, Status, UserId 的顺序创建的,而当前SELECT 的列顺序是PlanShiftId, UserId, Status,因此会造成混淆。

【讨论】:

    【解决方案2】:

    如果UserIdAssigneeId 尚未在基础表中引用User,则您有一个奇怪的数据模型。

    无论如何,您的where 子句是

    where (psi.UserId is not null and psi.UserId IN (select Id from dbo.[User])) or
          (ps.AssigneeId is not null and ps.AssigneeId IN (select Id from dbo.[User]))
    

    这留下了psi.UserId 匹配但ps.AssigneeId 不匹配的可能性。

    为确保逻辑匹配,请使用与select 中相同的表达式:

    where coalesce(ps.AssigneeId, psi.UserId) in (select Id from dbo.[User])
    

    【讨论】:

    • @KirillLudcev 。 . .在那种情况下,我认为失败的不是外键约束。
    【解决方案3】:

    可能是因为您在 WHERE 子句中指定了 OR,因此 AssigneeId 或 UserId 在 User 表中而不是另一个,因此使 FK 约束无效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-27
      • 2021-05-30
      • 1970-01-01
      相关资源
      最近更新 更多