实现子孙树查询的经典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  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值