3

可能重复:
SQL:按特定顺序从自引用表中删除数据

我需要从 SQL Server 2008 中的自引用表中删除一组记录。我正在尝试执行以下操作,但它不像 order by。

WITH SelfReferencingTable (ID, depth)
AS
(
   SELECT id, 0 as [depth]
   FROM dbo.Table
   WHERE parentItemID IS NULL AND [t].ColumnA = '123'
   UNION ALL
   SELECT [t].ID, [srt].[depth] + 1 
   FROM dbo.Table t 
   INNER JOIN SelfReferencingTable srt ON [t].parentItemID = [srt].id
   WHERE [t].ColumnA = '123'       
)   
DELETE y FROM dbo.Table y
JOIN SelfReferencingTable x on x.ID = y.id
ORDER BY x.depth DESC

任何想法为什么这不起作用?

4

2 回答 2

4

您无需按任何特定顺序删除它们。

只需一次操作即可将它们全部删除。在语句末尾检查约束。

假设您的递归 CTE 代码正确识别了您需要删除的所有行,您可以使用

WITH SelfReferencingTable (ID)
AS
(
   SELECT id
   FROM dbo.Table
   WHERE parentItemID IS NULL AND [t].ColumnA = '123'
   UNION ALL
   SELECT [t].ID 
   FROM dbo.Table t 
   INNER JOIN SelfReferencingTable srt ON [t].parentItemID = [srt].id
   WHERE [t].ColumnA = '123'       
)   
DELETE 
FROM dbo.Table 
WHERE ID IN (SELECT id FROM SelfReferencingTable )
于 2012-09-01T09:33:42.610 回答
0

子句delete不允许. order bydelete是一个单一的原子操作,操作步骤的完成顺序无关紧要delete

一个常见的解决方案是在循环中删除没有依赖行的行:

while 1=1
    begin
    delete  yt
    from    YourTable yt
    where   where ColumnA = '123'
            and not exists
            (
            select  *
            from    YourTable yt2
            where   yt2.parentItemId = yt.id
            )

    if @@rowcount = 0
        break
    end
于 2012-08-31T15:33:42.550 回答