I have a table which has hierarchy in it.
Lets start with Id = 5
; this is the child. (a given start parameter - from user)
Algorithm:
- give me the
first
value which you have encountered forid = 5
- if you haven't found value for
id = 5
, go to its parent and give me hisid
- if this parent also doesn't have a value - go to its parent ... etc (until parent has no parent -
parentId = 0
)
p.s. the result here should be 7.
if 7 value was empty so : 9
end if 9 was also empty so : 1
I'm trying to do this with CTE but no success..
p.s. I want a solution with CTE. :)
What I have tried (don't even look at it - it doesn't work):
WITH cte AS (
SELECT
id,VALUE,parentid
FROM [test].[dbo].[tmp] WHERE id=5
UNION ALL
SELECT
id,VALUE,parentid
FROM [tmp] WHERE parentId=cte.parentId ) //ERROR : The multi-part identifier "cte.parentId" could not be bound.
SELECT * FROM cte