无法创建第二个级联FK关系

时间:2015-05-19 18:16:25

标签: sql sql-server foreign-keys foreign-key-relationship

我有以下表格:

CREATE TABLE [dbo].[Memberships](
    [MembershipId] [int] IDENTITY(1,1) NOT NULL,
    [GroupId] [int] NOT NULL,
    [UserId] [int] NOT NULL,
    [IsUserAdmin] [bit] NOT NULL
 )

CREATE TABLE [dbo].[Gifts](
    [GiftId] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](100) NOT NULL,
    [MembershipId] [int] NOT NULL,
    [ClaimedByMembershipId] [int] NULL
 )

会员资格可以包含许多与之相关的礼物。删除成员资格时,我需要做两件事:

  1. 删除与该MembershipId相关联的所有礼物。
  2. 对于ClaimedByMembershipId等于被删除的成员资格的MembershipId的任何记录,请将ClaimedByMembershipId设置为NULL
  3. 我正在尝试通过Management Studio的UI实现此级联。我可以通过以下方式完成#1:

    ALTER TABLE [dbo].[Gifts]  WITH CHECK ADD  CONSTRAINT [FK_Gifts_Memberships] 
    FOREIGN KEY([MembershipId])
    REFERENCES [dbo].[Memberships] ([MembershipId])
    ON DELETE CASCADE
    GO
    

    对于#2,我在创建密钥后无法保存表格,我相信这看起来像这样:

    ALTER TABLE [dbo].[Gifts]  WITH CHECK ADD  CONSTRAINT [FK_Gifts_Memberships1] 
    FOREIGN KEY([ClaimedByMembershipId])
    REFERENCES [dbo].[Memberships] ([MembershipId])
    ON NULL CASCADE
    GO
    

    我收到以下错误:

    'Memberships' table saved successfully
    'Gifts' table
    - Unable to create relationship 'FK_Gifts_Memberships1'.  
    Introducing FOREIGN KEY constraint 'FK_Gifts_Memberships1' on table 'Gifts' may cause cycles 
    or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify 
    other FOREIGN KEY constraints.
    Could not create constraint. See previous errors.
    

    提前致谢。

1 个答案:

答案 0 :(得分:0)

嗯,这就像错误说的那样。您无法创建循环级联路径。如果TableA可能导致TableB上的级联删除,则TableB不会导致TableA上的级联删除。期。即使在您的特定情况下,它在逻辑上似乎应该没问题,SQL Server也不会允许它。无法覆盖。

你能做的最好就是用触发器处理你的#2要求。