层次结构表查询

时间:2013-06-28 09:47:30

标签: sql-server-2008

我有一个层次结构表,如下所示:

id  child_id
1   2
2   3
2   4
3   5
3   6
3   7
4   8
4   9
4   10

如何编写查询以获得这种格式的结果:

1
|_ 2
   |_ 3
   |  |_ 5
   |  |_ 6
   |  |_ 7
   |_ 4
      |_ 8
      |_ 9
      |_ 10

1 个答案:

答案 0 :(得分:1)

这是我能做的最好的事情:

WITH cte AS (
SELECT id, CAST(NULL AS INT) as Parent, 1 AS Level, CAST(id AS varchar(255)) AS LevelChar FROM Hier WHERE id = 1
UNION ALL
SELECT child_id AS id, hier.id AS Parent, Level + 1, CAST(LevelChar + '-' + CAST(child_id AS varchar(255)) AS varchar(255)) FROM Hier 
JOIN cte ON Hier.id = cte.id
)
SELECT ISNULL(REPLICATE(Space(2) + '|',Level-1),'') + CAST(id AS Varchar(255)) FROM cte
ORDER BY LevelChar, ID