最近做一个项目涉及到商品分类信息的管理,采用树的形式来实现,即在数据库中每个条目信息包括一个ID和ParentID,在删除树的一个子树的时候遇到一个问题就是,在删除一个节点时要保存他的所有子节点,以便进一步删除,但是SQL没有数组的概念,只有用游标来实现,并通过存储过程的递归实现删除子树
go
create procedure TreeDeleteByID(@id int)
as declare @num int;
declare @temp int;
begin
select @num = count(*) from [分类信息表] where [ParentID] = @id;
if @num > 0
begin
---必须将游标定义为local,否则递归时会出现游标已定义的问题
declare categoryCursor cursor local for select [ID] from [分类信息表] where [ParentID]= @id;
--打开游标
open categoryCursor;
--将缓存中的值取出到@temp
fetch categoryCursor into @temp;
while (@@fetch_status = 0)
begin
exec TreeDeleteByID @temp;
--取下一条记录
fetch next from categoryCursor into @temp;
end
deallocate categoryCursor;
end
delete from [分类信息表]where [ID] = @id;
end
go
本文介绍了一种使用SQL存储过程实现递归删除数据库中树形结构的方法。该方法通过定义局部游标并利用递归调用来遍历并删除指定节点的所有子节点。

被折叠的 条评论
为什么被折叠?



