0

我正在使用 SQL Server 2008 Express R2,并且我有一个自引用的表,因为我有一个层次结构。

我需要删除一个根节点,但由于外键而出现错误。我读过我可以使用两个选项,使用递归 CTE 或使用 a 而不是删除触发器。

两者的区别是什么?哪个更有效率?

谢谢。

4

1 回答 1

1

当您说使用删除触发器而不是递归 CTE 时,我假设您将在触发器中执行某种循环,这意味着 CTE 会更有效。

对于 CTE,请尝试以下操作:

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
于 2013-04-09T08:55:30.763 回答