答案 0 :(得分:1)
这可能是您的问题的解决方案,而不使用递归CTE
DECLARE @T TABLE (IdTech INT, IdTechFK INT, Name VARCHAR(255))
INSERT INTO @T VALUES
(1, NULL, 'FRT'),
(2, 1, 'FRT_1'),
(3, 1, 'FRT_2'),
(4, NULL, 'GSC filters'),
(5, 4, 'GSC filters_1'),
(6, 4, 'GSC filter_2'),
(7, 1, 'FRT_3'),
(8, 1, 'FRT_4'),
(9, NULL, 'Power Control')
SELECT a.IdTech, a.IdTechFK, a.Name
FROM (
SELECT m.IdTech, m.IdTechFK, m.Name, m.IdTech AS r FROM @T AS m
WHERE m.IdTechFK IS NULL
UNION ALL
SELECT c.IdTech, c.IdTechFK, c.Name, c.IdTechFK AS r FROM @T AS c
WHERE c.IdTechFK IS NOT NULL) AS a
ORDER BY a.r, idtech, IdTechFK
结果
+-------+---------+--------------+
|IdTech |IdTechFK |Name |
+-------+---------+--------------+
|1 |NULL |FRT |
|2 |1 |FRT_1 |
|3 |1 |FRT_2 |
|7 |1 |FRT_3 |
|8 |1 |FRT_4 |
|4 |NULL |GSC filters |
|5 |4 |GSC filters_1 |
|6 |4 |GSC filter_2 |
|9 |NULL |Power Control |
+-------+---------+--------------+