有时候我们需要按照分组递归查询,比如省市区,同一个省同一个市的要放到一起显示,而我们原始数据又不是这样排列的,所以需要我们做一下处理,测试数据:
--测试数据 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'河北省',0 union all select 2,N'陕西省',0 union all select 3,N'石家庄市',1 union all select 4,N'桥东区',3 union all select 5,N'唐山市',1 UNION all select 6,N'西安市',2 UNION all select 7,N'雁塔区',6 Go --测试数据结束
利用CTE的写法,来实现分组递归查询的功能,查看代码如下:
;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
结果:
以上实现了递归并分组显示的需求。