是相同的递归CTE和触发而不是删除?

时间:2013-04-09 08:29:08

标签: sql-server sql-server-2008r2-express

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

我需要删除根节点,但由于外键我收到错误。我已经读过我可以使用两个选项,使用递归CTE o使用而不是删除触发器。

两者之间有什么区别?哪个更有效率?

感谢。

1 个答案:

答案 0 :(得分: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