Recursive CTE-Find all Employees Below Manager

后端 未结 1 1636
走了就别回头了
走了就别回头了 2021-01-20 22:45

I created a sample fiddle for this SQLFIDDLE

CREATE TABLE [dbo].[Users](
    [userId] [int] ,
    [userName] [varchar](50) ,
    [managerId] [int] ,
   )

INSERT         


        
1条回答
  •  不思量自难忘°
    2021-01-20 23:44

    Try this. Filter has to be applied in the Anchor query of CTE

    WITH UserCTE
         AS (SELECT userId,
                    userName,
                    managerId,
                    0 AS EmpLevel
             FROM   [Users]
             WHERE  managerId = 3
             UNION ALL
             SELECT usr.userId,
                    usr.userName,
                    usr.managerId,
                    mgr.[EmpLevel] + 1
             FROM   [Users] AS usr
                    INNER JOIN UserCTE AS mgr
                            ON usr.managerId = mgr.userId
             WHERE  usr.managerId IS NOT NULL)
    SELECT *
    FROM   UserCTE AS u
    ORDER  BY EmpLevel; 
    

    FIDDLE DEMO

    0 讨论(0)
提交回复
热议问题