Skip to content

Instantly share code, notes, and snippets.

@taufikherjanto
Last active March 15, 2021 08:47
Show Gist options
  • Save taufikherjanto/253258dfc2c07c29119ab1eff81a6408 to your computer and use it in GitHub Desktop.
Save taufikherjanto/253258dfc2c07c29119ab1eff81a6408 to your computer and use it in GitHub Desktop.
CTE Tree Path WBS
WITH wbsproject(id, NAME, parentid, level, treepath) AS (
SELECT id,
NAME,
parentid,
0 AS LEVEL,
Cast(NAME AS VARCHAR(1024)) AS treepath
FROM port_project
WHERE parentid = 0
UNION ALL -- and now for the recursive part
SELECT d.id,
d.NAME,
d.parentid,
wbsproject.level + 1 AS LEVEL,
Cast(wbsproject.treepath + ' / ' + Cast(d.NAME AS VARCHAR(1024)) AS VARCHAR(1024)) AS treepath
FROM port_project d
INNER JOIN wbsproject
ON wbsproject.id = d.parentid
)
SELECT * FROM wbsproject ORDER BY treepath;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment