ON CASCADE DELETE在同一个表之间存在多对多关系

时间:2018-06-22 08:42:16

标签: sql-server tsql cascading-deletes

在我的SQL数据库中,我为M对M关系创建了以下表格

User
ID username userpass

User_Relationship
ID user1ID, user2ID

因此,user1ID是用户ID的外键,而user2ID也是如此。我想要做的是,当我从ID为1的用户删除一行时,我也想从User_Relationship中删除其中user1ID或user2ID为1的行,但仅删除那一行,而不删除其他任何行。我已经尝试将User_Relationship表中的两个外键都设为ON CASCADE DELETE,但是我收到以下错误消息:

Introducing FOREIGN KEY constraint on table 'User_Relationship' may cause
cycles or multiple cascade paths

那么我该如何从User表中删除一个值,并删除User_Relationship中其中user1ID或user2ID都将外键设置为User ID的每一行?我正在使用SQL Management Studio。谢谢。

1 个答案:

答案 0 :(得分:0)

  

我可以使用它:表:A => PK a_id B => PK b_id A_B =>

CREATE TABLE [dbo].[A_B](
    [a_id] [int] NOT NULL,
    [b_id] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_A_B] PRIMARY KEY CLUSTERED 
(
    [a_id] ASC,
    [b_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER TABLE [dbo].[A_B]  WITH CHECK ADD  CONSTRAINT [FK_a_b_b] FOREIGN KEY([A_Id])
REFERENCES [dbo].[A] ([a_id]) on delete cascade
GO

ALTER TABLE [dbo].[A_B] CHECK CONSTRAINT [FK_a_b_b]
GO

ALTER TABLE [dbo].[A_B]  WITH CHECK ADD  CONSTRAINT [FK_a_b_a] FOREIGN KEY([B_Id])
REFERENCES [dbo].[B] ([b_Id]) on delete cascade
GO

ALTER TABLE [dbo]。[A_B]检查约束[FK_a_b_a]     开始