尝试编写递归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。
答案 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
点数:
BusinessHierarchy
使用表别名的道具,但它们并未一直使用,它们应尽可能简短。在定义它们时,您不需要使用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