T-Sql 递归查询

使用CTE查询递归层级:(Sql CTE Recursion)

 1 WITH CTE_MA AS 
 2 (
 3     SELECT 0 AS Tier, EmployeeID, ManagerID, FirstName, LastName
 4     FROM dbo.MyEmployees
 5     WHERE EmployeeID = 1
 6     UNION ALL
 7     SELECT a.Tier+1 AS Tier, e.EmployeeID, e.ManagerID, e.FirstName, e.LastName
 8     FROM dbo.MyEmployees e
 9     INNER JOIN CTE_MA a ON e.ManagerID = a.EmployeeID
10 )
11 SELECT * FROM CTE_MA

 

Tier        EmployeeID ManagerID   FirstName                      LastName
----------- ---------- ----------- ------------------------------ ----------------------------------------
0           1          NULL        Ken                            Sánchez
1           273        1           Brian                          Welcker
2           16         273         David                          Bradley
2           274        273         Stephen                        Jiang
2           285        273         Syed                           Abbas
3           286        285         Lynn                           Tsoflias
3           275        274         Michael                        Blythe
3           276        274         Linda                          Mitchell
3           23         16          Mary                           Gibson

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。