Simulate a LEVEL column
The level column can be easily modeled by increasing the counter in the recursive part:
WITH tree (empid, name, level) AS ( SELECT empid, name, 1 as level FROM emp WHERE name = 'Joan' UNION ALL SELECT child.empid, child.name, parent.level + 1 FROM emp as child JOIN tree parent on parent.empid = child.mgrid ) SELECT name FROM tree;
Modeling order siblings by
Imitating order siblings by bit more complicated. Assuming we have a sort_order column that defines the order of elements per parent (and not a general sort order - because then order siblings not needed), then we can create a column that gives us a general sort order:
WITH tree (empid, name, level, sort_path) AS ( SELECT empid, name, 1 as level, cast('/' + right('000000' + CONVERT(varchar, sort_order), 6) as varchar(max)) FROM emp WHERE name = 'Joan' UNION ALL SELECT child.empid, child.name, parent.level + 1, parent.sort_path + '/' + right('000000' + CONVERT(varchar, child.sort_order), 6) FROM emp as child JOIN tree parent on parent.empid = child.mgrid ) SELECT * FROM tree order by sort_path;
The expression for sort_path looks so complicated that SQL Server (at least the version you are using) does not have a simple function to format numbers with leading zeros. In Postgres, I would use an integer array so that conversion to varchar not necessary, but this also does not work in SQL Server.
source share