我有一个父/子表(简单树)表结构(ID,ParentID),我想删除(并获取ID)给定父ID的所有子项 - 类似于这篇文章{{3} }。
在我获得当前ID的循环中,我还将使用此ID执行其他操作。
有人能给我一个SPROC的例子来实现这个目标吗?
由于
答案 0 :(得分: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
);