开发者

SP Help (Invalid Column Name)

With a MS SQL Stored Procedure I am getting the fol开发者_运维知识库lowing error "Invalid Column Name NavigationID".

Can anyone let me know what I am doing incorrectly?

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;


With the code you posted you get.

Msg 208, Level 16, State 1, Line 10
Invalid object name 'ParentID'.

Change FROM ParentID to FROM Parent.

You also need a column NavigationID in table Nav.

Try this:

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;

Result:

NavigationID
------------
3
1

Replace @Nav with whatever table you are using. @Nav is only here so that this code can be copied and tested.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜