1
我有如下表:現在爲什麼我的觸發器不會觸發?
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.
賓果。 @OP:請記住,在任何AFTER觸發器觸發之前,CASCADES都已解析,並且在使用DML觸發器時,FOR DELETE只是AFTER DELETE的別名。 – womp 2010-01-12 03:04:24
我必須說,很煩人的是,SQL Server不夠聰明,無法識別我可能想在單個表內強制執行內部參照完整性:( – 2010-01-12 10:11:16