SQL SERVER recursive query (4) - recursive hierarchical query

      When we are doing recursive queries, sometimes we need to query a certain level of data. If our data is not marked with the number of levels of the data, then we can add one ourselves when recursing, and read it as Use query conditions to test data:

--Test Data  
if not object_id(N'Tempdb..#T') is null  
    drop table #T  
Go  
Create table #T([Id] int,[Name] nvarchar(24),[FatherId] int)  
Insert #T  
select 1,N'Hebei Province',0 union all  
select 2,N'Shaanxi Province',0 union all  
select 3,N'Shijiazhuang City',1 union all  
select 4,N'Qiaodong District',3 union all  
select 5,N'Tangshan City',1 UNION all  
select 6,N'Xi'an',2 UNION all  
select 7,N'Yanta District',6  
Go  
-- end of test data  

      For example, if we want to read city-level data, the query code is as follows:

;WITH cte AS (
SELECT *,1 AS [level] FROM #T WHERE FatherId=0
UNION ALL
SELECT #T.*,cte.level+1 FROM #T JOIN cte ON cte.Id = #T.FatherId
)
SELECT * FROM cte WHERE [level]=2

      The result is as follows:


      In this way, we implement recursive hierarchical query.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325807949&siteId=291194637