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

来源:互联网 发布:淘宝店铺哪里购买 编辑:程序博客网 时间:2024/04/30 05:52
  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