The trigger based solution will be:
CREATE TRIGGER tr_Hierarchy_DeleteChildren ON Hierarchy FOR DELETE AS DELETE FROM Hierarchy WHERE ID IN ( SELECT DISTINCT h.ID FROM deleted d INNER JOIN Hierarchy h ON h.ObjectNode.IsDescendantOf(d.ObjectNode) = 1 EXCEPT SELECT ID FROM deleted )
EXCEPT ensures that we do not end an infinite recursive loop. In my own implementations, I actually set the flag in the context information that is triggered by the trigger, and then checks this flag at the start of the trigger and returns earlier if the flag is already set. This is not necessary, but slightly better for performance.
Alternatively, if you do not want to use a trigger, you can put the following logic in a stored procedure:
CREATE PROCEDURE DeleteHierarchyTree @ParentID hierarchyid AS DELETE FROM Hierarchy WHERE ID.IsDescendantOf(@ParentID) = 1
It seems a lot simpler at first, but keep in mind that people should remember to use this. If you do not have a trigger, and someone does a direct DELETE in the hierarchy table instead of going through the SP, it can very easily overpower your child records without knowing until it is too late.
Aaronaught
source share