SQL 遞歸查詢 (WITH AS )

一、環境 SQL Sever 2014

二、創建表並插入數據


CREATE TABLE [department](
	[ID] [int] NULL,
	[Name] [nchar](10) NULL,
	[parentid] [int] NULL
)  

 

三、使用with as 進行遞歸查詢

with w as
(
   select a.ID,a.Name,A.parentid from department A where A.ID=1
   union all
   select b.* from department B inner join  w on b.parentid=w.ID
)
select * from w;

查詢結果:

1	部門1       	0
3	部門3       	1
4	部門2       	3

四、使用 FOR XML PATH拼接ID

with w as
(
   select a.ID,a.Name,A.parentid from department A where A.ID=1
   union all
   select b.* from department B inner join  w on b.parentid=w.ID
)
select ','+convert(nvarchar,w.ID) from w for xml path('')

結果

,1,3,4

五、使用STUFF去除','

with w as
(
   select a.ID,a.Name,A.parentid from department A where A.ID=1
   union all
   select b.* from department B inner join  w on b.parentid=w.ID
)
select stuff((select ','+convert(nvarchar,w.ID) from w for xml path('')),1,1,'')

查詢結果:

1,3,4

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章