SQL server - climb up in the tree structure

Posted by Vytas999 on Stack Overflow See other posts from Stack Overflow or by Vytas999
Published on 2010-03-18T15:47:02Z Indexed on 2010/03/18 16:01 UTC
Read the original article Hit count: 262

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about sql-server

Related posts about tree