TSQL级联删除子记录?(TSQL Cascade delete for child records

2019-09-28 10:43发布

我有一个父/子表(简单的树)的表结构(ID,PARENTID),在这里我想删除(并获得的ID),所有的孩子对于一个给定父ID -类似于这篇文章的SQL服务器,级联删除和家长/子表 。

在循环期间,在那里我有电流ID,我也将执行与此ID的其他行动。

有人可以给我的存储过程的例子来做到这一点?

谢谢

Answer 1:

假设,你在SQL Server 2005中,这里是存储过程来实现这一点(通过使用CTE)的例子:

CREATE PROCEDURE [DeleteRecordWithChild]
    @id int
AS
BEGIN
    WITH Nodes ([Id], [ParentId], [Level]) 
    AS (
        SELECT  T.[Id], T.[ParentId], 0 AS [Level]
        FROM    [dbo].[YourTable] T
        WHERE   T.[Id] = @id

        UNION ALL

        SELECT  T.[Id], T.[ParentId], N.[Level] + 1
        FROM    [dbo].[YourTable] T
                INNER JOIN Nodes N ON N.[Id] = T.[ParentId]
    )

    DELETE
    FROM    [YourTable]
    OUTPUT  deleted.*
    WHERE   [Id] IN (
        SELECT  TOP 100 PERCENT N.[Id] 
        FROM    Nodes N
        ORDER BY N.[Level] DESC
    );
END

这会消除定义的行@id参数与表中的所有子节点并返回被删除的值在单个动作的处理应用。

您也可以返回删除的行到一个表变量(应CTE之前定义):

DECLARE @deleted_rows TABLE
(
    [Id] int,
    [ParentId] int,
    [Level] int
);

接着

DELETE
FROM    [YourTable]
OUTPUT  deleted.* INTO @deleted_rows
WHERE   [Id] IN (
    SELECT  TOP 100 PERCENT N.[Id] 
    FROM    Nodes N
    ORDER BY N.[Level] DESC
);


文章来源: TSQL Cascade delete for child records?