TSQL Cascade delete for child records?

谁都会走 提交于 2019-12-11 09:55:02

问题


I have a parent/child table (simple tree) table structure (ID, ParentID), where I want to delete (and get the ID of) all children for a given parent ID - similar to this post sql server, cascade delete and parent/child table .

During the loop, where I've got the current ID, I will also be performing other actions with this ID.

Can someone give me an example of the SPROC to accomplish this?

Thanks


回答1:


Assuming, you're on SQL SERVER 2005, here is the example of stored procedure to accomplish this (by using 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

This removes a row defined by @id parameter with all child nodes from the table and returns the deleted values to the processing application in a single action.

You also could return deleted rows into a table variable (should be defined before CTE):

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

and then

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
);


来源:https://stackoverflow.com/questions/1732465/tsql-cascade-delete-for-child-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!