views:

32

answers:

1

One table has name "Stages", every Stage can have 0..infinity childrens, in table Stages there are column named Parent. This column is foreigh key for same table Stages. How to make cascade deleting in this tree? I want to on deleting any row in this table, auto delete all their childrens and childrens of their childrens....etc

При таком запросе

..............................
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.
A: 

Add foreigns key with ON DELETE CASCADE option for all "child" tables.

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

for new tables:

CREATE TABLE ttt
(
  ...
  CONSTRAINT YOurConstraintName 
  FOREIGN KEY (YourParentId)
  REFERENCES YourParentTable(ParentTableId) ON DELETE CASCADE
)
Michael Pakhantsov
How to do this using MS SQL Enterprise manager 2005 express?
Evl-ntnt
This works only on distinguish tables. When table link on itself this not work
Evl-ntnt
@Evl-ntnt, its works for tables which have link to itself. May you provide information what you did, and what is exactly does not works?
Michael Pakhantsov
I read that not works on sql.rutomorrow I will try it again and message youthanx
Evl-ntnt
Можно по русски?
Evl-ntnt
Evl-ntnt
Я проверил в Oracle там всё работает. Реально вся цепь удаляется каскадом. Завтра проверю в mssql. Отпишусь. на sql.ru речь о mysql
Michael Pakhantsov
Обновил самый первый пост. Видимо действительно нельзя использовать каскадное удаление при рекурсии. Может триггер можно написать какой нибудь?
Evl-ntnt
Глянь сюда http://stackoverflow.com/questions/1783700/sql-server-self-reference-fk-trigger-instead-of-on-delete-cascade
Michael Pakhantsov
Спасибо. Если отредактируешь свой первый ответ то я смогу плюсик поставить
Evl-ntnt