У меня есть следующая таблица:
if object_id(N'dbo.Node') is null
create table dbo.Node
(
ID bigint identity primary key,
ParentID bigint null foreign key references Node(ID) on delete no action,
DateCreated datetime not null,
LastUpdated datetime not null,
[Name] nvarchar(500) not null,
);
Теперь, поскольку SQL Server жалуется, когда я пытаюсь установить внешний ключ как каскадное удаление, я создал триггер, чтобы выполнить работу:
create trigger Node_Delete on Node for delete
as
begin
delete from Node where ParentID in (select id from deleted)
end
Теперь вот примерный набор данных:
ID ParentID DateCreated LastUpdated Name
520 1 2010-01-12 02:26:26.890 2010-01-12 02:26:26.890 Test 1
523 520 2010-01-12 02:32:44.777 2010-01-12 02:32:44.777 Test 2
Теперь давайте запустим этот бит SQL:
delete from Node where ID=520
Узел должен быть удален вместе с дочерним узлом. Так почему я получаю эту ошибку?
Msg 547, Level 16, State 0, Line 1
The DELETE statement conflicted with the SAME TABLE REFERENCE constraint "FK__Node__ParentID__117F9D94". The conflict occurred in database "mydb", table "dbo.Node", column 'ParentID'.
The statement has been terminated.