递归通用 table 表达式 (CTE) 引用不允许提示。考虑从递归 CTE 参考中删除提示 'CTE'

Hints are not allowed on recursive common table expression (CTE) references. Consider removing hint from recursive CTE reference 'CTE'

我有一名员工table这里是table结构

Name    varchar
GUID    numeric
ParentGUID  numeric

这是一些示例数据

NAME GUID ParentGUID
ABC    1   NULL
BCD    2   1
xyz    3   2
PQR    4   2
MRS    5   3

此 table 包含员工和经理的大层次结构。 我需要挑选特定员工下的所有员工。 前任。我需要所有员工都在 BCD 下,所以结果应该是

 xyz    3   2
 PQR    4   2

这是我的递归查询。

;WITH CTE (Name, GUID, ParentGUID)
    AS
    (
    select distinct B.Name , B.GUID,  B.ParentGUID
    FROM 
    EMP B with (nolock)     

    union All

    select a.Name , a.GUID, a.ParentGUID
    FROM EMP a with (nolock)
    inner join CTE C with (nolock)  on a.ParentGUID = c.GUID
    )
    select *
    FROM CTE B with (nolock)     where B.Name in ('BCD')

但它给我错误。

Msg 4150, Level 16, State 1, Line 1
Hints are not allowed on recursive common table expression (CTE) references. Consider removing hint from recursive CTE reference 'CTE'.

谁能帮我更正这个查询。

您的 where B.Name in ('BCD') 将您的结果集过滤为仅一行。将其更改为以下内容,您应该会得到想要的结果:

;with cte (Name, GUID, ParentGUID)
    as
    (
    select distinct B.Name
                   ,B.GUID
                   ,B.ParentGUID
    from EMP B
    where B.Name in ('BCD')

    union All

    select a.Name
          ,a.GUID
          ,a.ParentGUID
    from EMP a
        inner join CTE C
            on a.ParentGUID = c.GUID
    )
    select *
    from CTE