Monday, December 21, 2009

Writing recursive queries in SQL server 2005 using Common table expression (CTE)


with cte (empID,manID,depth,hierarchy) as
(
select e.employeeID,e.managerID ,, cast(e.employeeID asnvarchar(max))as hierarchy
from humanresources.Employee as e
where managerID is null


union all


select emp.employeeID,emp.managerID ,depth+1  , hierarchy + ‘/’+cast(emp.employeeID as nvarchar(max)) as hierarchy
from humanresources.Employee emp
inner join cte
on emp.managerID=cte.empID
)


select * from cte order by depth

No comments:

Post a Comment