在MS SQL Server Express 2005中删除级联树

时间:2010-08-05 15:34:47

标签: sql-server cascade delete-row sql-server-2005-express

一个表的名称为“Stages”,每个Stage可以有0到infinity的孩子。在表“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.

1 个答案:

答案 0 :(得分: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
)