Hierarchy of Employee with CTE

  1. create table #tblemployee  (  
  2.       empid   varchar(10) primary key  
  3.     , empname varchar(10)  
  4.     , mgrid   varchar(10)  
  5.   )   
  6.   
  7. insert into #tblemployee   
  8. select 'Emp001''Satish'NULL union all  
  9. select 'Emp002''Amit''Emp001'  union all  
  10. select 'Emp003''Sumit''Emp001' union all  
  11. select 'Emp004''Anil''Emp002' union all  
  12. select 'Emp005''Tarun''Emp003' union all  
  13. select 'Emp006''Sandeep''Emp003' union all  
  14. select 'Emp007''Abhay''Emp006' union all  
  15. select 'Emp008''Deepak''Emp002' union all  
  16. select 'Emp009''Suman''Emp007' union all  
  17. select 'Emp010''Raman''Emp007'  
  18.   
  19. ;with reportees as (  
  20.     select empid, empname, mgrid, 1 as level  
  21.     from   #tblemployee       
  22.     where  mgrid = 'Emp001'  
  23.     union all  
  24.     select #tblemployee.empid, #tblemployee.empname, #tblemployee.mgrid, level + 1  
  25.     from   #tblemployee, reportees  
  26.     where  #tblemployee.mgrid = reportees.empid  
  27. )  
  28.   
  29. select    a.empid, a.empid, a.mgrid, b.empname as mgrname, level  
  30. from    reportees a  
  31. left join #tblemployee b on a.mgrid = b.empid  
  32. order by level  
  33.   
  34. drop table #tblemployee