SqlServer父节点与子节点查询及递归

  1. /*  
  2. 标题:sql server中递归的实现  
  3. 作者:axin  
  4. 时间:2012-3-24  
  5. */  
  6. set nocount on  
  7. if OBJECT_ID('tb','U'is not null drop table tb  
  8. go  
  9. create table tb(ID int,PID INT)  
  10. insert into tb  
  11. select 1,0 union all  
  12. select 2,1 union all  
  13. select 3,2 union all  
  14. select 4,3 union ALL  
  15. select 5,4 union ALL  
  16. select 6,5 union ALL  
  17. select 7,6   
  18. --自定义函数方式实现父节点查询子节点  
  19. if OBJECT_ID('GetChildID'is not null drop function GetChildID  
  20. go  
  21. create function GetChildID(@ParentID int)  
  22. returns @t table(ID int)  
  23. as  
  24.   begin  
  25.      insert into @t select ID from tb where PID=@ParentID  
  26.      while @@rowcount<>0  
  27.      begin  
  28.         insert into @t select a.ID from tb as a   
  29.         inner join @t as b  
  30.         on a.PID=b.ID  
  31.         and not exists(select 1 from @t where ID=a.ID)  
  32.      end  
  33.      return   
  34.   end  
  35. go  
  36. select * from dbo.GetChildID(1)  
  37. --自定义函数方式实现子节点查询父节点  
  38. if OBJECT_ID('GetParentID'is not null drop function GetParentID  
  39. go  
  40. create function GetParentID(@ChildID int)  
  41. returns @t table(PID int)  
  42. as  
  43.   begin  
  44.      insert into @t select PID from tb where ID=@ChildID  
  45.      while @@rowcount<>0  
  46.      begin  
  47.         insert into @t select a.PID from tb as a   
  48.         inner join @t as b  
  49.         on a.ID=b.PID  
  50.         and not exists(select 1 from @t where PID=a.PID)  
  51.      end  
  52.      return   
  53.   end  
  54. go  
  55. select * from dbo.GetParentID(3)  
  56. --公用表表达式实现父节点查询子节点(SqlServer2005+)  
  57. DECLARE @ParentID int  
  58. SET @ParentID=1  
  59. with CTEGetChild as  
  60. (  
  61. select * from tb where PID=@ParentID  
  62. UNION ALL  
  63.  (SELECT a.* from tb as a inner join  
  64.   CTEGetChild as b on a.PID=b.ID  
  65.  )  
  66. )  
  67. SELECT * FROM CTEGetChild  
  68. --公用表表达式实现子节点查询父节点(SqlServer2005+)  
  69. DECLARE @ChildID int  
  70. SET @ChildID=6  
  71. DECLARE @CETParentID int  
  72. select @CETParentID=PID FROM tb where ID=@ChildID  
  73. with CTEGetParent as  
  74. (  
  75. select * from tb where ID=@CETParentID  
  76. UNION ALL  
  77.  (SELECT a.* from tb as a inner join  
  78.   CTEGetParent as b on a.ID=b.PID  
  79.  )  
  80. )  
  81. SELECT * FROM CTEGetParent  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值