Saturday, April 19, 2008

Tree view of hierarchy using the cte

One of the uses of Common type expression

WITH
Hierarchy(EmployeeId,Employeename,Parentid,Hlevel)

AS (SELECT EmployeeId,

Employeename,

Parentid,

0 AS Hlevel

FROM OrgEntitiesMaster

WHERE Parentid = 0

UNION ALL

SELECT H.EmployeeId,

H.Employeename,

H.Parentid,

Hlevel + 1

FROM OrgEntitiesMaster H

INNER JOIN HIERARCHY P

ON H.Parentid = P.EmployeeId

)

SELECT *

FROM HIERARCHY

No comments:

Post a Comment