前言:
在实际开发中,我们经常需要根据一个父节点获取所有的子节点,也就是所谓的递归.有的时候也需要根据子节点,获取它的父节点.
下面我介绍两种方式实现上面的需求:
用户自定义函数方式(sql Server 2000+) 公用表表达式方式(sql Server 2005+) HIErarchyID方式(sql Server 2008+)--待研究实现:
/*标题:sql server中递归的实现作者:axin时间:2012-3-24*/set nocount onif OBJECT_ID('tb','U') is not null drop table tbgocreate table tb(ID int,PID INT)insert into tbselect 1,0 union allselect 2,1 union allselect 3,2 union allselect 4,3 union ALLselect 5,4 union ALLselect 6,5 union ALLselect 7,6 --自定义函数方式实现父节点查询子节点if OBJECT_ID('GetChildID') is not null drop function GetChildIDgocreate function GetChildID(@ParentID int)returns @t table(ID int)as begin insert into @t select ID from tb where PID=@ParentID while @@rowcount<>0 begin insert into @t select a.ID from tb as a inner join @t as b on a.PID=b.ID and not exists(select 1 from @t where ID=a.ID) end return endgoselect * from dbo.GetChildID(1)--自定义函数方式实现子节点查询父节点if OBJECT_ID('GetParentID') is not null drop function GetParentIDgocreate function GetParentID(@ChildID int)returns @t table(PID int)as begin insert into @t select PID from tb where ID=@ChildID while @@rowcount<>0 begin insert into @t select a.PID from tb as a inner join @t as b on a.ID=b.PID and not exists(select 1 from @t where PID=a.PID) end return endgoselect * from dbo.GetParentID(3)--公用表表达式实现父节点查询子节点(sqlServer2005+)DECLARE @ParentID intSET @ParentID=1with CTEGetChild as(select * from tb where PID=@ParentIDUNION ALL (SELECT a.* from tb as a inner join CTEGetChild as b on a.PID=b.ID ))SELECT * FROM CTEGetChild--公用表表达式实现子节点查询父节点(sqlServer2005+)DECLARE @ChildID intSET @ChildID=6DECLARE @CETParentID intselect @CETParentID=PID FROM tb where ID=@ChildIDwith CTEGetParent as(select * from tb where ID=@CETParentIDUNION ALL (SELECT a.* from tb as a inner join CTEGetParent as b on a.ID=b.PID ))SELECT * FROM CTEGetParent总结
以上是内存溢出为你收集整理的SqlServer父节点与子节点查询及递归全部内容,希望文章能够帮你解决SqlServer父节点与子节点查询及递归所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)