递归CTE在SQL Server中查找层次结构中的第一个管理器

问题描述 投票:0回答:1

我有一个用户表

enter image description here

而且我想通过工作位置层次结构为每个用户找到他们的第一位经理。

我设法编写了此脚本,但似乎无法使其正常运行。我需要用户1003必须具有1001 managerId。现在显示1002。

enter image description here

select 1001 as userid, 'L1' as locationCode, NULL as parentLocationCode, 1 as isManager into #Users union all
select 1002 as userid, 'L2' as locationCode, 'L1' as parentPad, 0 as isManager union all
select 1003 as userid, 'L3' as locationCode, 'L2' as parentPad, 0 as isManager 

;WITH cte_org AS (
    SELECT       
        d.userid 
        ,d.locationCode
        ,d.parentLocationCode
        ,d.isManager
        ,null as managerId
    FROM       
        #Users as d
    WHERE d.parentLocationCode is NULL
    UNION ALL
    SELECT 
        d.userid 
        ,d.locationCode
        ,d.parentLocationCode
        ,d.isManager
        ,o.userid as managerId
    FROM 
        #Users as d
        inner JOIN cte_org o on d.parentLocationCode=o.locationCode
)
SELECT *
FROM cte_org
OPTION (MAXRECURSION 32767);

我有一个用户表,我想通过工作位置层次结构为每个用户查找他们的第一位管理员。我设法编写了此脚本,但似乎无法使其正常运行。我需要...

sql sql-server recursion common-table-expression
1个回答
0
投票

您尝试的问题是,您没有跟踪起点,就您而言,是经理。只需将启动经理添加为新列即可:

© www.soinside.com 2019 - 2024. All rights reserved.