网站首页  汉语字词  英语词汇  考试资料  写作素材  旧版资料

请输入您要查询的考试资料:

 

标题 SQL语句实现子孙树查询经典实例
内容
    下面介绍的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
随便看

 

在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。

 

Copyright © 2002-2024 cuapp.net All Rights Reserved
更新时间:2025/5/14 2:29:58