实现子孙树查询的经典SQL语句

数据库 SQL Server
使用SQL语句可以实现子孙树查询,下面就为您介绍该SQL语句的写法,希望对您学习SQL语句的使用能够有所帮助。

下面介绍的SQL语句非常经典,该SQL语句实现子孙树查询,该SQL语句可以直接在查询分析器中执行,供您参考。

  1. --生成表  
  2. create table MENU(id int,mname char(50),parent int)  
  3.  
  4. --插入数据  
  5. insert into MENU   
  6. select 1,'新闻',Null union all  
  7. select 2,'房产',Null union all  
  8. select 3,'科技新闻',1 union all  
  9. select 4,'社会新闻',1 union all  
  10. select 5, 'IT新闻',3 union all  
  11. select 6, '航天新闻',3   
  12.  
  13. --实现查询新闻子孙树  
  14. Declare @s varchar(1000)   
  15. select @s=','+cast(id as varchar(20))+'' from MENU where id=1 
  16.  
  17. while  @@rowCount>0   
  18.  
  19. --charindex:返回字符串中指定表达式的起始位置  
  20.   select   @s=@s+','+cast(id as varchar) from MENU       
  21.             where charindex(','+cast(id as varchar)+',',@s+',')=0    
  22.    
  23.             and   charindex(','+cast(parent as varchar)+',',@s+',')>0   
  24.  
  25.  
  26. select * from MENU where charindex(','+cast(id as varchar)+',',@s+',')>0  
  27.  
  28. --删除表  
  29.  
  30. drop table MENU  

 

 

 

【编辑推荐】

查询表结构的SQL语句

使用SQL语句查询时间段

巧用SQL语句删除重复记录

批量执行SQL语句的示例

教您使用SQL语句修改SQL主键

 

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

2010-10-21 10:28:13

SQL Server查

2018-11-05 14:54:18

MySQLSQL语句数据库

2010-09-26 15:23:24

SQL语句

2010-10-27 17:00:32

oracle树查询

2010-10-21 12:16:11

SQL Server查

2010-09-17 10:08:18

SQL中case wh

2019-11-06 09:30:35

SQL查询语句数据库

2017-09-07 16:20:39

SQL查询语句查询优化

2010-09-07 10:35:38

SQL语句

2010-09-28 14:33:13

SQL语句

2018-05-14 10:50:13

SQL查询语句神经网络

2010-09-25 16:53:39

SQL语句

2010-09-26 15:15:11

SQL语句

2010-09-28 11:28:40

SQL字段属性

2010-09-24 19:23:51

SQL查询时间段

2010-10-21 14:27:35

SQL Server时

2022-07-28 09:13:30

MySQL数据库

2010-09-26 09:01:18

SQL强类型查询

2011-09-08 16:30:59

SQL Server查询

2011-03-17 13:54:42

查询参数SQL语句利用率
点赞
收藏

51CTO技术栈公众号