Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 是相同的递归CTE和触发器而不是delete吗?_Sql Server_Sql Server 2008r2 Express - Fatal编程技术网

Sql server 是相同的递归CTE和触发器而不是delete吗?

Sql server 是相同的递归CTE和触发器而不是delete吗?,sql-server,sql-server-2008r2-express,Sql Server,Sql Server 2008r2 Express,我使用的是SQL Server 2008 Express R2,我有一个自引用的表,因为我有一个层次结构 我需要删除一个根节点,但由于外键,我得到了一个错误。我已经读到我可以使用两个选项,使用递归CTE来使用而不是delete触发器 他们俩的区别是什么?哪个更有效 谢谢。当您说使用删除触发器而不是递归CTE时,我假设您将在触发器中执行某种循环,这意味着CTE将更有效 对于CTE,请尝试以下操作: with cte as ( select id as root, parent, id

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

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

他们俩的区别是什么?哪个更有效


谢谢。

当您说使用删除触发器而不是递归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实现删除触发器。是的,这就是我所理解的CTE,因为我看到的另一个选项是替代删除触发器,它有不同的代码,但我不知道它们是否相同。