显示分层记录时出现问题(SQL Server 2005)[基于SET]

时间:2010-06-28 03:20:29

标签: sql-server-2005

我可以进行查询以获取Master -Chile记录。但是如何以层次结构的方式显示它们。任何例子都有帮助

我正在使用SQL Server 2005

1 个答案:

答案 0 :(得分:0)

有更多的方法,但这种快速修改将起作用:

;With bottomupParentChild AS 
( 
    SELECT EmpId AS parents, ReportsTo,CAST(EmpName AS VARCHAR(1000)) AS [Path],  0 AS [Level], EmpName 
    FROM @Employees 
    WHERE EmpId = @childNode 
    UNION ALL 
    SELECT i.EmpId AS parents, i.ReportsTo, CAST(gp.[Path] + '/' + i.EmpName AS VARCHAR(1000)) AS [Path],  
         gp.[Level]+1 AS [Level],i.EmpName 

    FROM @Employees i 
    JOIN bottomupParentChild gp ON i.EmpId = gp.ReportsTo 
) 
, cteRows (TotalRows)
 as (select count(*) - 1 from bottomupParentChild)

SELECT ABS(Level - TotalRows), REPLICATE('    ', ABS(Level - TotalRows)) + EmpName as [Hierarchy] 
FROM bottomupParentChild 
 cross join cteRows
ORDER BY  [Path] desc; 

我添加了第二个cte,它获取第一个cte中的行数,并使用它来“翻转”层次结构。