Question

I am using SQL Server 2008 Express R2 and I have a table that is self referencing, because I have a hierarchy struct.

I need to delete a root node, but I get an error because of foreign key. I have read that I can use two option, use a recursive CTE o use a instead of delete trigger.

Which is the difference brtween both of them? which is more efficient?

Thanks.

Was it helpful?

Solution

When you say use a delete trigger as opposed to a recursive CTE, I assume you are going to do some kind of loop in the trigger, which would mean the CTE would be more efficient.

For a CTE, try something like:

with cte as (
    select id as root, parent, id
    from [<YourTable>]
    where parent is null -- This selects root nodes

    union all

    select cte.root, d.parent, d.id
    from cte
    inner join data d on cte.id = d.parent
)
delete from [<YourTable>]
from [<YourTable>]
inner join cte on rel.id = cte.id
where cte.root = 1 -- This is the root to delete
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top