views:

110

answers:

1

Hello. I have some sql table, named Object, which saves tree data in fields ObjectID, ParentID, and others. I have implemented recurse procedure, which select everything down by objectID from tree, like this:

1.
1.1.
1.2.
1.2.1.
...

Now o need to "Climb up" - by some ObjectID i need to select everything Up, like this:

1.2.1.
1.2.
1.

How i can do that?

In example, my "down" procedure looks like:

ALTER PROCEDURE [dbo].[Object_SelectDownByRoot_Simple]
@ObjectID int

AS
WITH tree (ObjectID, ParentID, ObjectName, ObjectCode) AS
(
    SELECT  ObjectID, ParentID, ObjectName, ObjectCode
     FROM dbo.[ObjectQ] ofs
     WHERE( ObjectID = @ObjectID )

     UNION ALL

     SELECT     ofs.ObjectID, ofs.ParentID, ofs.ObjectName, ofs.ObjectCode
      FROM dbo.[ObjectQ] ofs
      JOIN tree ON tree.ObjectID = ofs.ParentID
)

SELECT  
ObjectID, ParentID, ObjectName, ObjectCode
FROM tree
A: 

Is this for Microsoft SQL Server 2005? 2008?

Try something like this;

CREATE PROCEDURE getParentIDs
ID as int,
level as int
AS
GO

ALTER PROCEDURE getParentIDs
ID as int,
level as int
AS

DECLARE @P as int /* <-- change to your ObjectID datatype */

SELECT @P=ParentID FROM tree WHERE ObjectID = ID

SELECT @P, level
UNION ALL
getParentIDs , 1+level   /* <-- this might not work... :-/ */
GO
Simon B.
This does not work, i get the error list:Msg 102, Level 15, State 1, Procedure getParentIDs, Line 2Incorrect syntax near 'ID'.Msg 102, Level 15, State 1, Procedure getParentIDs, Line 3Incorrect syntax near 'ID'.Msg 102, Level 15, State 1, Procedure getParentIDs, Line 13Incorrect syntax near 'getParentIDs'.
Vytas999