有以下數據表sql

假如咱們要查詢ID爲003的數據的全部子節點咱們可使用CTE 遞歸查詢完成...spa
- 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.net
轉自:http://blog.csdn.net/myxx520/article/details/6922682blog