1

我有一个父/子表(简单树)表结构(ID,ParentID),我想删除(并获取)给定父 ID 的所有子表的 ID - 类似于这篇文章sql server, cascade delete and parent /子表

在获得当前 ID 的循环期间,我还将使用此 ID 执行其他操作。

有人可以给我一个 SPROC 的例子来完成这个吗?

谢谢

4

1 回答 1

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
);
于 2010-05-14T15:51:42.337 回答