[英]SQL recursive CTE query error 'invalid column name - level'
Trying to write a recursive CTE query, keep getting the following error: level, invalid column name
尝试编写递归CTE查询时,始终出现以下错误: level, invalid column name
This is the query, where am I going wrong? 这是查询,我哪里出错了?
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
This is ms sql server 2005. 这是ms sql server 2005。
There's three issues with what you posted: 您发布的内容存在三个问题:
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
Points: 要点:
BusinessHierarchy
to itself, when the reference should be the CTE name 您将BusinessHierarchy
加入自身时,引用应为CTE名称 Props for using table aliases, but they weren't consistently used, and they should be as brief as possible. 有关使用表别名的道具,但并没有得到一致使用,因此应尽可能简短。 You don't need to use the AS
when defining them, just a matter of style on that part. 定义它们时不需要使用AS
,这只是样式方面的问题。
I'm thinking the table aliases will deal with the level
column not being found issue, but not 100%. 我认为表别名将处理level
列未找到的问题,但不是100%。
You need OwnerHierarchy
somewhere in the second half of the CTE to be recursive. 您需要在CTE下半年的某个地方OwnerHierarchy
才能递归。 Instead, you have BusinessHierarchy
twice. 相反,您有两次BusinessHierarchy
。
Just guessing at the exact requirements, but something like this. 只是猜测确切的要求,但是类似这样。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.