Sql Server遞歸查詢(轉)

有以下數據表sql

 

 

假如咱們要查詢ID爲003的數據的全部子節點咱們可使用CTE 遞歸查詢完成...spa

 

[sql]  view plain copy print ?
 
  1. if OBJECT_ID('tb','N') is not null  
  2.  drop table tb;  
  3.   
  4.   
  5. create table tb(id varchar(3) , pid varchar(3) , name varchar(10));  
  6. insert into tb values('001' , null , '廣東省');  
  7. insert into tb values('002' , '001' , '廣州市');   
  8. insert into tb values('003' , '001' , '深圳市') ;  
  9. insert into tb values('004' , '002' , '天河區') ;  
  10. insert into tb values('005' , '003' , '羅湖區');  
  11. insert into tb values('006' , '003' , '福田區') ;  
  12. insert into tb values('007' , '003' , '寶安區') ;  
  13. insert into tb values('008' , '007' , '西鄉鎮') ;  
  14. insert into tb values('009' , '007' , '龍華鎮');  
  15. insert into tb values('010' , '007' , '鬆崗鎮');  
  16.   
  17. select * from tb;  
  18.   
  19.  with cte as  
  20.  (  
  21.  select a.id,a.name,a.pid from tb a where id='003'  
  22.  union all   
  23.  select k.id,k.name,k.pid  from tb k inner join cte c on c.id = k.pid  
  24.  )select * from cte  
  25.    


查詢結果以下:
003 深圳市 001
005 羅湖區 003
006 福田區 003
007 寶安區 003
008 西鄉鎮 007
009 龍華鎮 007
010 鬆崗鎮 007.net

 

 

 

轉自:http://blog.csdn.net/myxx520/article/details/6922682blog

相關文章
相關標籤/搜索