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  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章