SQL語句實現(xiàn)子孫樹查詢經(jīng)典實例

字號:


    下面介紹的SQL語句非常經(jīng)典,該SQL語句實現(xiàn)子孫樹查詢,該SQL語句可以直接在查詢分析器中執(zhí)行,供您參考。
    --生成表
    create table MENU(id int,mname char(50),parent int)
    --插入數(shù)據(jù)
    insert into MENU
    select 1,'新聞',Null union all
    select 2,'房產(chǎn)',Null union all
    select 3,'科技新聞',1 union all
    select 4,'社會新聞',1 union all
    select 5, 'IT新聞',3 union all
    select 6, '航天新聞',3
    --實現(xiàn)查詢新聞子孫樹
    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