sqlserver的CTE实现递归查询

--递归查询
IF OBJECT_ID('DiGui','U') IS NOT NULL 
    DROP TABLE DiGui
CREATE TABLE DiGui(
Id VARCHAR(50),
ParentId VARCHAR(50)
)
INSERT INTO dbo.DiGui( Id, ParentId )
select '第三层','第一层'
union select '第二层','第一层'
union select '第四层','第一层'
union select '第十层','第二层'
union select '第九层','第二层'
union select '第八层','第五层'
union select '第二十层','第四层'
union select '第二十二层','第四层'
union select '第三十层','第二十层'
union select '第三十二层','第二十层'
union select '第四十层','第三十层'
union select '第四十二层','第三十层'
union select '第五十层','第四十层'
union select '第五十二层','第四十层'
union select '第八十层','第五十层'
union select '第八十二层','第五十层'
union select '第一百层','第九十层'
union select '第一百零二层','第九十层'

;with temp
as
(
select Id, parentid
from DiGui
where [parentid] = '第一层'
union all
select a.Id, a.parentid
from DiGui a
inner join temp on a.[parentid] = temp.[Id]
)
select * from temp
原文地址:https://www.cnblogs.com/xiaozhi1236/p/6874848.html