Sql Server遞迴查詢

來源:互聯網
上載者:User

標籤:

有如下資料表

 

 

假如我們要查詢ID為003的資料的所有子節點我們可以使用CTE 遞迴查詢完成...

 

[sql] view plaincopyprint? 
  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

 

 

 

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

Sql Server遞迴查詢(轉)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.