SQL遍历父子关系表的测试


  本文标签:SQL遍历父子关系表

  SQL遍历父子关系表的方法未必人人都知道,下面就为您介绍一个SQL遍历父子关系表的测试,希望可以让您对SQL遍历父子关系表有更深的认识  。

  --建立测试环境

  1. Create Table A  
  2. (ID Int,  
  3. fatherID Int,  
  4. Name Varchar(10)  
  5. )  
  6. Insert A Select 1,        NULL,       tt  
  7. Union All Select 2,        1,          aa  
  8. Union All Select 3,        1,          bb  
  9. Union All Select 4,        2,          cc  
  10. Union All Select 5,        2,          gg  
  11. Union All Select 6,        4,          yy  
  12. Union All Select 7,        4,          jj  
  13. Union All Select 8,        7,           ll  
  14. Union All Select 9,        NULL, uu  
  15. Union All Select 10,       9,         oo  
  16. GO 

  --建立函数

  1. Create Function GetChildren(@ID Int)  
  2. Returns @Tree Table (ID Int, fatherID Int, Name Varchar(10))  
  3. As  
  4. Begin  
  5. Insert @Tree Select ID, fatherID, Name From A Where fatherID = @ID  
  6. While @@Rowcount > 0  
  7. Insert @Tree Select A.ID, A.fatherID, A.Name From A A Inner Join @Tree B On A.fatherID = B.ID And A.ID Not In (Select ID From @Tree)  
  8. Return  
  9. End  
  10. GO  

  --测试

  1. Select * From dbo.GetChildren(1)  
  2. GO 

  --刪除测试环境

  1. Drop Table A  
  2. Drop Function GetChildren 

  --结果

  1. /*  
  2. IDfatherIDName  
  3. 21aa  
  4. 31bb  
  5. 42cc  
  6. 52gg  
  7. 64yy  
  8. 74jj  
  9. 87ll  
  10. */