I have a hierarchical query to track a reporting structure. This almost works, except that it’s not reporting the very top level node, probably because the top-level people “report” to themselves.
The query is:
select
level,
empid,
parentid
from usertable
connect by nocycle prior parentid= empid
start with empid = 50
This produces:
LEVEL EMPID PARENTID
------ ----- --------
1 50 258
2 258 9555
3 9555 17839
I’m not getting a level 4, since it would look like:
4 17839 17839
Without changing data, is there a way to modify my query so that all 4 levels are returned? The goal is to get the empids, so I can do a check for
id in (hierarchical subquery)
BTW, if I remove the nocycle from the query I get an error.
Chris,
You only get 3 rows because your top level row is not set the way it should to handle hierarchical queries. Typically the top level row, or president KING in Oracle’s well known EMP table, has no manager. In your case you should not set the parentid of 17389 to 17389 itself, but to NULL. Either update the table accordingly, or use a view to accomodate for this situation.
An example:
This part of the EMP table has four levels with its top level row (7839) set to itself. The same as your empid 17839. And this leads to only three rows using your query:
Either use a (inline) view to set the mgr/parentid column to null for the top level:
Or fix your data with an UPDATE statement:
And you can leave out the NOCYCLE keyword as well, after you are done fixing.
Regards,
Rob.