【问题标题】:is the same recursive CTE and trigger instead of delete?是相同的递归 CTE 和触发器而不是删除?
【发布时间】:2013-04-09 08:29:07
【问题描述】:

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

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

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

谢谢。

【问题讨论】:

  • 你比较苹果和鸵鸟。您可以实现您的删除触发器使用递归CTE。

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


【解决方案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

【讨论】:

  • 是的,这就是我所理解的 CTE,因为我看到的另一个选项是代替删除触发器,它有不同的代码,但我不知道它们是否相同.
猜你喜欢
  • 2021-04-10
  • 2011-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-16
  • 2014-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多