SQL SERVER recursive query (3) - group recursion

      Sometimes we need to recursively query by group, such as provinces and cities, the same province and the same city should be displayed together, and our original data is not arranged in this way, so we need to do some processing and test the 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

      Use the writing method of CTE to realize the function of group recursive query. Check the code as follows:

;WITH    t AS ( SELECT   * ,
                        CAST(RIGHT('000' + CAST([Id] AS VARCHAR), 3) AS VARCHAR(MAX)) AS sort
               FROM     #T
               WHERE    [FatherId] = 0
               UNION ALL
               SELECT   #T.* ,
                        CAST(sort + RIGHT('000' + CAST(#T.[Id] AS VARCHAR),
                                          3) AS VARCHAR(MAX))
               FROM     t
                        INNER JOIN #T ON t.Id = #T.FatherId
             )
SELECT Id,Name,FatherId FROM t ORDER BY sort

      result:


      The above realizes the requirement of recursion and group display.

Guess you like

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