>  기사  >  데이터 베이스  >  SQL语句实现子孙树查询经典实例

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

WBOY
WBOY원래의
2016-06-07 14:54:312062검색

下面介绍的 SQL语句 非常 经典 ,该 SQL语句实现 子孙树 查询 ,该 SQL语句 可以直接在 查询 分析器中执行,供您参考。 --生成表 createtableMENU(idint,mnamechar(50),parentint) --插入数据 insertintoMENU select1,'新闻',Nullunionall select2,'房产',

下面介绍的SQL语句非常经典,该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

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.