海纳百川,有容乃大
善于总结,积累软财富

【标题】经典SQL语句实现子孙树查询

【内容】
 实现的SQL语句:可以直接在查询分析器中执行

--生成表
create table MENU(id int,mname char(50),parent int)

--插入数据
insert into MENU
select 1,'新闻',Null union all
select 2,'房产',Null union all
select 3,'科技新闻',1 union all
select 4,'社会新闻',1 union all
select 5, 'IT新闻',3 union all
select 6, '航天新闻',3

--实现查询新闻子孙树
Declare @s varchar(1000)
select @s=','+cast(id as varchar(20))+'' from MENU where id=1

while  @@rowCount>0

--charindex:返回字符串中指定表达式的起始位置
  select   @s=@s+','+cast(id as varchar) from MENU    
            where charindex(','+cast(id as varchar)+',',@s+',')=0 
 
            and   charindex(','+cast(parent as varchar)+',',@s+',')>0


select * from MENU where charindex(','+cast(id as varchar)+',',@s+',')>0

--删除表

drop table MENU

【标签】树结构菜单 树结构表 子孙树查询 经典SQL语句


 

posted on 2007-04-27 18:04  海纳百川  阅读(1927)  评论(2编辑  收藏  举报

首页原创.NET区 div1
.NET新手区 div2
精华区 div3
专家区 div4
读书心得区 div5
百度主题实验室
百度主题推广 div7

-->