實(shí)現(xiàn)子孫樹查詢的經(jīng)典SQL語句
作者:佚名
使用SQL語句可以實(shí)現(xiàn)子孫樹查詢,下面就為您介紹該SQL語句的寫法,希望對(duì)您學(xué)習(xí)SQL語句的使用能夠有所幫助。
下面介紹的SQL語句非常經(jīng)典,該SQL語句實(shí)現(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,'社會(huì)新聞',1 union all
- select 5, 'IT新聞',3 union all
- select 6, '航天新聞',3
- --實(shí)現(xiàn)查詢新聞子孫樹
- Declare @s varchar(1000)
- select @s=','+cast(id as varchar(20))+'' from MENU where id=1
- while @@rowCount>0
- --charindex:返回字符串中指定表達(dá)式的起始位置
- 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
【編輯推薦】
責(zé)任編輯:段燃
來源:
互聯(lián)網(wǎng)