I have the following table (ObjectStates) and want to get the root as well as the first-child of the root:
ID Title ParentID
1 Draft null
2 Green null
3 Red null
4 Foo 1
5 Bar 4
6 Some1 1
7 Some2 6
8 XYZ 2
9 Some3 7
I would like the following output:
GetState(5)
-- returns root: 1, first-child: 4
GetState(6)
-- returns root: 1, first-child: 6
GetState(7)
-- returns root: 1, first-child: 6
GetState(9)
-- returns root: 1, first-child: 6
GetState(8)
-- returns root: 2, first-child: 8
So no matter how deep in the hierarchy I am querying - I always want the root element as well as the first child element. If you would consider this tree, I always want the red and blue elements, no matter how deep in the tree I am.
I can get the "root" states like so:
WITH CTEHierarchy
AS (
SELECT
ID
,0 AS LEVEL
,ID AS root
FROM ObjectStates
WHERE ParentID IS NULL
UNION ALL
SELECT
ObjectStates.ID
,LEVEL + 1 AS LEVEL
,[root]
FROM ObjectStates
INNER JOIN CTEHierarchy uh ON uh.id = ObjectStates.ParentID
)
SELECT [root]
FROM CTEHierarchy
WHERE ID = @ObjectStateID
Which gives me my desired root results:
GetState(5)
-- returns root: 1
GetState(9)
-- returns root: 1
GetState(2)
-- returns root: 2
How can I traverse up from there? So get the next child in the tree from root? Or the other way around - get the root as well as the first level. Recursion is breaking my head.