新建一张Prog的表,表结构如下:
现在要遍历表中的子节点,并删除所有子节点
--创建用户定义函数 Create function f_getChild_prog(@ID VARCHAR(10)) returns @t table(ID VARCHAR(10),ParentID vARCHAR(10),Level INT) as begin declare @i int,@ret varchar(8000) set @i =1 insert into @t select ID,ParentID,@i from Prog where ParentID = @ID while @@rowcount<>0 begin set @i = @i + 1 insert into @t select a.ID,a.ParentID,@i from Prog a,@t b where a.ParentID=b.ID and b.Level = @i -1 end return end go --创建用户定义存储过程 create procedure sp_relationDel_Prog(@var varchar(100)) as begin declare @ID varchar(100) while CHARINDEX(',',@var)>0 begin set @ID = LEFT(@var,CHARINDEX(',',@var)-1) set @var = STUFF(@var,1,CHARINDEX(',',@var),'') delete Prog where ID in (select ID from f_getChild_prog(@ID)) end delete Prog where ID in(select ID from dbo.f_getChild_prog(@var)) end go --执行删除 exec sp_relationDel_Prog '15'
为了测试先插入一条数据
INSERT INTO Prog (ID) VALUES(1000)
INSERT INTO Prog (ID) VALUES(2000)
删除多条数据的方法
Delete from Prog where ID=2000 OR ID=1000 (注意是OR)
仅作查询子节点用
SELECT * FROM Prog; WITH CityTree AS ( SELECT * from Prog where ParentID = 2--需要查找的父节点 UNION ALL SELECT Prog.* from Citytree JOIN Prog on CityTree.id = Prog.ParentID ) SELECT * FROM CityTree;
类似的帖子:http://blog.csdn.net/qq282030166/article/details/51429474
以下未测试:
一篇遍历父子关系数据的表(二叉树)获得所有子节点 所有父节点及节点层数函数 :
http://blog.csdn.net/geovindu/article/details/6730439
另外一篇:sql删除树节点 及其子节点的全部(存储过程,游标,递归)
http://www.cnblogs.com/shuai0147/articles/2378103.html