2

尝试编写递归 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。

4

3 回答 3

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. BusinessHierarchy当引用应该是 CTE 名称时,您正在加入自身
  3. CTE与原始表的关系需要正确,方向正确

使用表别名的道具,但它们并没有被一致使用,它们应该尽可能简短。定义它们时不需要使用AS,只是那部分的风格问题。

结论


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

于 2010-01-09T06:29:49.067 回答
2

您需要OwnerHierarchy在 CTE 的后半部分进行递归。相反,你有BusinessHierarchy两次。

于 2010-01-08T20:20:00.883 回答
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
于 2010-01-08T20:22:12.657 回答