I have a table that store recursive records through two fields: ID and PARENTID.
I have a functionality that can associate a parent to an element of the tree. When I select the elements that can be “parent” of myself I shall obviously exclude from the resulting list all the elements which, directly or indirectly, depends on me but also the elements from which I already depend.
Let’s make an example. Given the following sample hierarchy:
ID PARENT_ID
----------- ------------------
1 NULL
2 1
3 NULL
4 2
5 1
6 3
If I would like to find the elements that can be parent of element with ID = 4 I shall consider only elements 5 - 3 - 6 because they do not have any relation with the actual structure.
How can I get those elements with a CTE query?
1 Answer