下面介绍的 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