使用MS SQL存储过程我收到以下错误“无效的列名称NavigationID”。
有谁能让我知道我做错了什么?
DECLARE @NavigationID INT
SET @NavigationID = 5
CREATE TABLE #tmp (NavigationID int , ParentID int);
INSERT INTO #tmp SELECT NavigationID, ParentID FROM Nav;
WITH Parent AS
(
SELECT NavigationID, ParentID FROM #tmp WHERE NavigationID = @NavigationID
UNION ALL
SELECT t.NavigationID, t.ParentID FROM Parent
INNER JOIN #tmp t ON t.NavigationID = Parent.ParentID
)
SELECT NavigationID FROM ParentID
WHERE NavigationID <> @NavigationID;
答案 0 :(得分:1)
使用您发布的代码即可获得。
Msg 208, Level 16, State 1, Line 10
Invalid object name 'ParentID'.
将FROM ParentID
更改为FROM Parent
。
您还需要表NavigationID
中的列Nav
。
试试这个:
declare @Nav table(NavigationID int, ParentID int)
insert into @Nav
select 1, null union all
select 2, 1 union all
select 3, 1 union all
select 4, 3 union all
select 5, 3 union all
select 6, null union all
select 7, 6
declare @NavigationID int;
set @NavigationID = 5;
with Parent as
(
select NavigationID,
ParentID
from @Nav
where NavigationID = @NavigationID
union all
select t.NavigationID, t.ParentID
from Parent
inner join @Nav t
on t.NavigationID = Parent.ParentID
)
select NavigationID
from Parent
where NavigationID <> @NavigationID;
结果:
NavigationID
------------
3
1
将@Nav替换为您正在使用的任何表。 @Nav仅在此处,以便可以复制和测试此代码。