开发者

Problem in displaying hierarchical records (SQL Server 2005) [SET BASED]

开发者 https://www.devze.com 2023-01-05 09:10 出处:网络
I can make query to get the Master -Chile records. But how to display them in hierarchial fashion. Any e开发者_如何学JAVAxample will help

I can make query to get the Master -Chile records. But how to display them in hierarchial fashion. Any e开发者_如何学JAVAxample will help

I am using SQL Server 2005


There are more elgeant ways, but this quick modification will work:

;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; 

I added a second cte that gets the count of rows from the first cte, and use it to "flip" the hierarchy.

0

精彩评论

暂无评论...
验证码 换一张
取 消