SQL递归CTE查询错误'无效列名 - 级别'

时间:2010-01-08 20:15:06

标签: sql sql-server-2005 common-table-expression

尝试编写递归CTE查询,不断收到以下错误:level, invalid column name

这是查询,我哪里错了?

WITH OwnerHierarchy AS (
   SELECT PairID, 
          ChildID, 
          ParentID, 
          0 AS level
     FROM BusinessHierarchy
   UNION ALL
   SELECT e.PairID, 
          e.ChildID, 
          e.ParentID, 
          level + 1 AS level
     FROM BusinessHierarchy AS e 
     JOIN BusinessHierarchy AS eh ON e.ParentID = eh.ParentID)
 SELECT PairID, 
        ChildID, 
        ParentID, 
        level
    FROM OwnerHierarchy AS OwnerHierarchy_1
 ORDER BY level, ChildID, ParentID

这是ms sql server 2005。

3 个答案:

答案 0 :(得分:3)

您发布的内容存在三个问题:

WITH OwnerHierarchy AS (
   SELECT a.pairid, 
          a.childid, 
          a.parentid, 
          0 AS level
     FROM BusinessHierarchy a
    WHERE a.parentid IS NULL -- Point #1, see below
   UNION ALL
   SELECT b.PairID, 
          b.ChildID, 
          b.ParentID, 
          oh.level + 1 AS level
     FROM BusinessHierarchy AS b
     JOIN OwnerHierarchy oh ON oh.childid = b.parentid) -- Points #2 & 3, see below
 SELECT x.PairID, 
        x.ChildID, 
        x.ParentID, 
        x.level
    FROM OwnerHierarchy x
 ORDER BY x.level, x.ChildID, x.ParentID

点数:

  1. UNION的上半部分缺少确定根节点/记录/行的内容。我已经假设,希望正确......
  2. 当引用应为CTE名称
  3. 时,您正在加入BusinessHierarchy
  4. CTE和原始表之间的关系需要正确,并且方向正确
  5. 使用表别名的道具,但它们并未一直使用,它们应尽可能简短。在定义它们时,您不需要使用AS,只是关于该部分的风格问题。

    结论


    我认为表别名将处理level列未找到问题,但不是100%。

答案 1 :(得分:2)

在CTE的后半部分某处需要OwnerHierarchy才能递归。相反,您有BusinessHierarchy两次。

答案 2 :(得分:1)

只是猜测确切的要求,但是这样的事情。

WITH OwnerHierarchy(PairID, ChildID, ParentID, level)
AS 
(
     SELECT PairID, ChildID, ParentID, 0 AS level
     FROM BusinessHierarchy
     WHERE ParentID IS NULL
     UNION ALL
     SELECT e.PairID, e.ChildID, e.ParentID, level + 1 AS level
     FROM BusinessHierarchy AS e 
     INNER JOIN OwnerHierarchy AS eh 
     ON e.ParentID = eh. ChildID
     )
 SELECT     PairID, ChildID, ParentID, level
 FROM         OwnerHierarchy AS OwnerHierarchy_1
 ORDER BY level, ChildID, ParentID