【问题标题】:Hints are not allowed on recursive common table expression (CTE) references. Consider removing hint from recursive CTE reference 'CTE'递归公用表表达式 (CTE) 引用不允许使用提示。考虑从递归 CTE 参考“CTE”中删除提示
【发布时间】:2016-10-19 11:09:21
【问题描述】:

我这里有一张Employee表是表结构

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'.

谁能帮我更正这个查询。

【问题讨论】:

  • 那么您可以删除 WITH(NOLOCK) 作为错误状态...
  • 谢谢,S.karras 删除 WITH(NOLOCK) 后,我只得到 1 条记录,我没有得到完整的层次结构

标签: sql-server tsql common-table-expression recursive-query


【解决方案1】:

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

【讨论】:

  • 您好,感谢@iamdave 的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-18
  • 2017-12-11
相关资源
最近更新 更多