Question : Creating a SQL or stored procedure to get hierarchy of employees listed under a manager

I have a EMP table  in the below fashion.

Emp_id      Emp Name      Mgr_id      Mgr_name

1            David            NULL      NULL
2            Andrew            1              David
3            Tom                    2              Andrew
4            Alex                    3              Tom
5            Randy            4              Alex
6            Mitchel            5              Randy
11            Harry            6              Mitchell
22            George            2              Andrew
44            Karen            3              Tom
55            William            4              Alex
66            Ross                    5              Randy
77            Joseph            6              Mitchell
88            Mark                    6              Mitchell
99            Paul                    6              Mitchell

All I need is a SQL which gives the results in the below format for a given employee based on the hierarchy. The way I should get the result is, for a given employee I have to get all the employee under him down the hierarchy. I have attached the hierarchy image file for further explanation.

Mgr_Nm      Emp_Name

Randy      Randy
Randy      Mitchell
Randy      Ross
Randy      Harry
Randy      Joseph
Randy      Mark
Randy      Paul
      
Tom      Tom
Tom      Karen
Tom      Randy
Tom      William
Tom      Mitchell
Tom      Ross
Tom      Harry
Tom      Joseph
Tom      Mark
Tom      Paul

Mitchell      Mitchell
Mitchell      Harry
Mitchell      Joseph
Mitchell      Mark
Mitchell      Paul


Can this be done by a direct SQL (or) do we have to create a stored proc/function for this? Please help me in achieving this.

Thanks in Advance
Attachments:
 
Hierarchy
Hierarchy
 
 
Data file
Data file
 

Answer : Creating a SQL or stored procedure to get hierarchy of employees listed under a manager

Yes, you can do this in direct SQL.  No, you do not have to create a stored proc/function for this.  You have to write a hierarchical query though, which (in Oracle) means you have to include the "connect by ... prior" clause and the "start with" clause, like this:

select mgr_name, emp_name
from emp
start with 'DAVID'
connect by prior emp_name = mgr_name;

You can (optionally) add this line:
order siblings by emp_name

(to put the employees for each manager in alphabetical order)

You can optionially start with a different manager's name if you only want the employees under that manager, and not all employees.
Random Solutions  
 
programming4us programming4us