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. */ 

 

 

 

 

【编辑推荐】

SQL Server视图的使用

SQL SERVER内部函数大全

SQL Server变量赋值的方法

详解SQL Server全局变量

动态sql中使用临时表的实例


分享标题:SQL遍历父子关系表的测试
当前URL:http://zjjierui.cn/article/cdisodh.html

其他资讯

售后响应及时

7×24小时客服热线

数据备份

更安全、更高效、更稳定

价格公道精准

项目经理精准报价不弄虚作假

合作无风险

重合同讲信誉,无效全额退款