Skip to content

Instantly share code, notes, and snippets.

@taufikherjanto
Last active March 15, 2021 07:29
Show Gist options
  • Save taufikherjanto/3c6f50ff66858ffddad392f7ae89d157 to your computer and use it in GitHub Desktop.
Save taufikherjanto/3c6f50ff66858ffddad392f7ae89d157 to your computer and use it in GitHub Desktop.
-- Using the REPLICATE function to indent with a '. ' for each level
WITH WBSProject(Id, name, Parentid, Level, TreePath) AS (
SELECT
id as 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 as 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 Id, Level, REPLICATE(' . ', Level) + name as Node
FROM WBSProject
ORDER BY TreePath;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment