Wednesday, June 8, 2016

Recursive CTEs in AdventureWorks 2008

With myCTE(BusinessEnityID,ManagerId,lv)

As(

Select BusinessEntityID,ManagerId,1 From HumanResources.Employee

where ManagerID is null

union all

Select e.BusinessEntityID, e.ManagerId, lv+1 from HumanResources.Employee e

join myCTE on e.ManagerID=myCTE.BusinessEnityID



)
 
Select emp.BusinessEntityID,emp.JobTitle, c.FirstName+' '+C.LastName as [Name],

M.FirstName+'' +M.LastName as [Manager],lv

from HumanResources.Employee emp

join myCTE

on emp.BusinessEntityID=myCTE.BusinessEnityID

join Person.Person as C

on c.BusinessEntityID=emp.BusinessEntityID

Left Join Person.Person as M

on emp.ManagerID=M.BusinessEntityID order by lv

No comments:

Post a Comment