I have the following table:
if object_id(N'dbo.Node') is null
create table dbo.Node
(
ID bigint identity primary key,
ParentID bigint null, -- references Node(ID)
DateCreated datetime not null,
LastUpdated datetime not null,
[Name] nvarchar(500) not null,
);
I have this trigger to achieve cascading deletes within the same table:
create trigger Node_Delete on Node for delete
as
begin
delete from Node where ParentID in (select id from deleted)
end
Here's my data set:
ID ParentID DateCreated LastUpdated Name
534 514 2010-01-12 10:15:03.940 2010-01-12 10:15:03.940 Test 1
535 534 2010-01-12 10:15:08.563 2010-01-12 10:15:08.563 Test 2
536 535 2010-01-12 10:15:12.063 2010-01-12 10:15:12.063 Test 3
537 536 2010-01-12 10:15:18.510 2010-01-12 10:15:18.510 Test 4
Now I perform this query:
delete from Node where ID=534
And this is the resultant data set:
ID ParentID DateCreated LastUpdated Name
536 535 2010-01-12 10:15:12.063 2010-01-12 10:15:12.063 Test 3
537 536 2010-01-12 10:15:18.510 2010-01-12 10:15:18.510 Test 4
Why does the DELETE statement in the trigger not cause a recursive execution of the trigger until all descended records are deleted?
EDIT: Note that I have posted a working solution below, but marked a different answer as correct, seeing as my question was not "what is the solution", but rather "why does the way I'm doing it not work".