Sql server 递归公共表表达式(CTE)引用上不允许使用提示。考虑从递归CTE引用和XX27删除提示;CTE&x27;

Sql server 递归公共表表达式(CTE)引用上不允许使用提示。考虑从递归CTE引用和XX27删除提示;CTE&x27;,sql-server,tsql,common-table-expression,recursive-query,Sql Server,Tsql,Common Table Expression,Recursive Query,我这里有一个员工表是表结构 Name varchar GUID numeric ParentGUID numeric 下面是一些示例数据 NAME GUID ParentGUID ABC 1 NULL BCD 2 1 xyz 3 2 PQR 4 2 MRS 5 3 此表包含员工和经理的大层次结构。 我需要选择特定员工下的所有员工。 我需要所有员工都接受BCD,所以结果应该是 xyz 3 2 PQR 4 2

我这里有一个员工表是表结构

Name    varchar
GUID    numeric
ParentGUID  numeric
下面是一些示例数据

NAME GUID ParentGUID
ABC    1   NULL
BCD    2   1
xyz    3   2
PQR    4   2
MRS    5   3
此表包含员工和经理的大层次结构。 我需要选择特定员工下的所有员工。 我需要所有员工都接受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'.

有人能帮我更正这个查询吗。

您的
其中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

嗯,您可以删除带有(NOLOCK)的记录,因为错误说明…谢谢,S.karras在删除带有(NOLOCK)的记录后,我只得到1条记录,我没有得到完整的层次结构。谢谢,@iamdave的帮助。