SQL遍历父子关系表的测试

数据库 SQL Server
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. */ 

 

 

 

 

【编辑推荐】

SQL Server视图的使用

SQL SERVER内部函数大全

SQL Server变量赋值的方法

详解SQL Server全局变量

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

责任编辑:段燃 来源: 互联网
相关推荐

2019-11-26 09:21:49

区块链比特币虚拟货币

2010-10-27 15:11:52

oracle递归查询

2018-04-16 15:11:30

2023-11-14 10:03:30

数据库技术

2010-09-07 14:36:24

SQL语句

2010-11-12 14:21:15

SQL函数

2010-09-09 13:32:14

SQL函数遍历

2012-02-02 16:13:29

HibernateJava

2010-11-11 10:41:03

sql server遍

2010-11-11 10:53:22

SQL Server遍

2010-11-11 11:00:06

sql server遍

2011-06-02 10:20:09

SQL主从关系

2020-11-11 10:13:08

PPID欺骗DLL注攻击

2010-09-14 15:51:15

sql遍历

2010-09-01 11:46:01

DB2临时表SQL

2011-08-23 10:54:16

PostgreSQL表空间用户

2010-11-24 13:11:06

MySQL遍历数据表

2010-09-09 16:40:58

SQL循环游标

2009-09-15 13:28:49

LINQ表间关系查询

2010-09-17 16:03:17

锁定SQL表
点赞
收藏

51CTO技术栈公众号