下面介绍的SQL语句非常经典,该SQL语句实现子孙树查询,该SQL语句可以直接在查询分析器中执行,供您参考。
--生成表 createtableMENU(idint,mnamechar(50),parentint) --插入数据 insertintoMENU select1,'新闻',Nullunionall select2,'房产',Nullunionall select3,'科技新闻',1unionall select4,'社会新闻',1unionall select5,'IT新闻',3unionall select6,'航天新闻',3 --实现查询新闻子孙树 Declare@svarchar(1000) select@s=','+cast(idasvarchar(20))+''fromMENUwhereid=1while@@rowCount>0 --charindex:返回字符串中指定表达式的起始位置 select@s=@s+','+cast(idasvarchar)fromMENU wherecharindex(','+cast(idasvarchar)+',',@s+',')=0 andcharindex(','+cast(parentasvarchar)+',',@s+',')>0 select*fromMENUwherecharindex(','+cast(idasvarchar)+',',@s+',')>0 --删除表 droptableMENU
【编辑推荐】
查询表结构的SQL语句
使用SQL语句查询时间段
巧用SQL语句删除重复记录
批量执行SQL语句的示例
教您使用SQL语句修改SQL主键