--序号递归
WITH RoulettePrizeItem
AS ( SELECT RowNum ,
EventId
FROM #tbRoulettePrizeItem
WHERE RowNum = 1
UNION ALL
SELECT d.RowNum ,
d.EventId
FROM RoulettePrizeItem tbrpi
INNER JOIN #tbRoulettePrizeItem d ON d.RowNum = tbrpi.RowNum + 1
--关联递归
假如我们要查询ID为003的数据的所有子节点我们可以使用CTE 递归查询完成...
[sql] view plaincopyprint?
if OBJECT_ID(‘tb‘,‘N‘) is not null
drop table tb;
create table tb(id varchar(3) , pid varchar(3) , name varchar(10));
insert into tb values(‘001‘ , null , ‘广东省‘);
insert into tb values(‘002‘ , ‘001‘ , ‘广州市‘);
insert into tb values(‘003‘ , ‘001‘ , ‘深圳市‘) ;
insert into tb values(‘004‘ , ‘002‘ , ‘天河区‘) ;
insert into tb values(‘005‘ , ‘003‘ , ‘罗湖区‘);
insert into tb values(‘006‘ , ‘003‘ , ‘福田区‘) ;
insert into tb values(‘007‘ , ‘003‘ , ‘宝安区‘) ;
insert into tb values(‘008‘ , ‘007‘ , ‘西乡镇‘) ;
insert into tb values(‘009‘ , ‘007‘ , ‘龙华镇‘);
insert into tb values(‘010‘ , ‘007‘ , ‘松岗镇‘);
select * from tb;
with cte as
(
select a.id,a.name,a.pid from tb a where id=‘003‘
union all
select k.id,k.name,k.pid from tb k inner join cte c on c.id = k.pid
)select * from cte
查询结果如下:
003 深圳市 001
005 罗湖区 003
006 福田区 003
007 宝安区 003
008 西乡镇 007
009 龙华镇 007
010 松岗镇 007
来源: <http://blog.csdn.net/myxx520/article/details/6922682>