我有下表:
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.
答案 0 :(得分:3)
外键阻止初始删除,触发器永远不会触发。尝试使用INSTEAD OF触发器从最远的死者中删除。