First of all, I must thank to Maulik Dhorajia for his great post. That post saved me a lot.
That’s the @Company table we will use:
And here is the SQL Query we need to use:
-- Working Example ;WITH CTECompany AS ( SELECT EmpID, ParentID, PersonName , 0 AS HLevel, CAST(RIGHT(REPLICATE('_',5) + CONVERT(VARCHAR(20),EmpID),20) AS VARCHAR(MAX)) AS OrderByField FROM @Company WHERE ParentID IS NULL UNION ALL SELECT C.EmpID, C.ParentID, C.PersonName , (CTE.HLevel + 1) AS HLevel, CTE.OrderByField + CAST(RIGHT(REPLICATE('_',5) + CONVERT(VARCHAR(20),C.EmpID),20) AS VARCHAR(MAX)) AS OrderByField FROM @Company C INNER JOIN CTECompany CTE ON CTE.EmpID = C.ParentID WHERE C.ParentID IS NOT NULL ) -- Working Example SELECT EmpID , ParentID , HLevel , PersonName , (REPLICATE( '----' , HLevel ) + PersonName) AS Person FROM CTECompany ORDER BY OrderByField,PersonName;