Sql Server递归查询(转)
时间:2021-07-01 10:21:17
帮助过:2人阅读
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
Sql Server递归查询(转)
标签: