0

一个表的名称为“Stages”,每个 Stage 可以有 0 到无穷大的孩子。在“Stages”表中有一个名为“Parent”的列。此列是同一个表“Stages”的外键。

我将如何对这棵树进行级联删除?我想在删除此表中的任何行时,自动删除他们所有的孩子和他们孩子的孩子......

使用以下查询

GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Stage_Stage]') AND parent_object_id = OBJECT_ID(N'[dbo].[Stage]'))
ALTER TABLE [dbo].[Stage]  WITH CHECK ADD  CONSTRAINT [FK_Stage_Stage] FOREIGN KEY([parent])
REFERENCES [dbo].[Stage] ([id]) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Stage] CHECK CONSTRAINT [FK_Stage_Stage]
GO

我收到这个错误

Msg 1785, Level 16, State 0, Line 2
Introducing FOREIGN KEY constraint 'FK_Stage_Stage' on table 'Stage' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Msg 1750, Level 16, State 0, Line 2
Could not create constraint. See previous errors.
Msg 4917, Level 16, State 0, Line 1
Constraint 'FK_Stage_Stage' does not exist.
Msg 4916, Level 16, State 0, Line 1
Could not enable or disable the constraint. See previous errors.
4

1 回答 1

1

为所有“子”表添加带有 ON DELETE CASCADE 选项的外键。

ALTER TABLE SomeChildTable 
CONSTRAINT YOurConstraintName 
FOREIGN KEY (YourParentId)
REFERENCES YourParentTable(ParentTableId) ON DELETE CASCADE;

对于新表:

CREATE TABLE ttt
(
  ...
  CONSTRAINT YOurConstraintName 
  FOREIGN KEY (YourParentId)
  REFERENCES YourParentTable(ParentTableId) ON DELETE CASCADE
)
于 2010-08-05T15:39:11.863 回答