日期:2014-05-17  浏览次数:20380 次

SQL 无限极分类递归
根据数据库中出现的多个子类ID去查询父类第二级所有的ID,各位大神请赐教

------解决方案--------------------
if object_id('tb','U')is not null drop table tb
go
create table tb(ID int, ParentID int)
insert into tb select 1,0  
insert into tb select 2,1  
insert into tb select 3,1  
insert into tb select 4,2  
insert into tb select 5,3  
insert into tb select 6,5  
insert into tb select 7,6

;WITH cte AS
(
SELECT *,[level]=0 FROM tb WHERE ID=5 
UNION ALL
SELECT tb.*,[level]=[level]+1 from cte ,tb WHERE cte.ParentID=tb.ID
)
SELECT * FROM cte WHERE [level]=2

是这个第二级吗?

加了level 显示级,你在后面选择需要的级别就可以了
------解决方案--------------------
with t as
(
select * from tb where id in (8,9,10) union all 
select tb.id, tb.parentid from t, tb where tb.id=t.parentid
)
select distinct t.id from t,(select id from tb where parentid=1) b where t.id=b.id