SQL Recursive CTE hierarchy

Job ID: 33578735

Budget: $10 – $30 USD

I require a hierarchy table from a Work Breakdown Structure table.
I have a table WBS_DATA that contains columns of ID, Name, Parent ID and Sequence columns.

I require the hierarchy to be added to another table called WBSTREE with the LEVEL.

Note: when the hierarchy is generated the order in which the items must show falls under the sequence_sort column, I have users that add items to the hierarchy that need to fall into its correct levels and allocation.

In my Data you will notice ID 6580 has Parent of 6430 which is the first ID, this 6580 has child items 6581 and 6582 that will fall under it in the hierarchy .

I have tried using another SQL statement but cant get the sort order of the hierarchy correct. SQL file and Image of what the result must be.

Thank you

Attached the BAK file, SQL Data in Excel and the result in pdf required.

The following code I changed and applied to the WBS_Data table, it is very close to what I want the only part is it does not sort the child items ID 6580 in the correct place and does not include the Sequence column. If you can use this method it will be great.

CODE BELOW:

WITH Recursive_CTE AS (
SELECT
child.BusinessUnitID,
CAST(child.BusinessUnit as varchar(100)) BusinessUnit,
CAST(child.ParentUnitID as Int) ParentUnitID,
CAST(NULL as varchar(100)) ParentUnit,
CAST('>> ' as varchar(100)) LVL,
CAST(child.BusinessUnitID as varchar(100)) Hierarchy,
1 AS RecursionLevel

FROM WBSStructures child
WHERE BusinessUnitID = 6430

UNION ALL

SELECT
child.BusinessUnitID,
CAST(LVL + child.BusinessUnit as varchar(100)) AS BusinessUnit,
child.ParentUnitID,
parent.BusinessUnit ParentUnit,
CAST('>> ' + LVL as varchar(100)) AS LVL,
CAST(Hierarchy + ':' + CAST(child.BusinessUnitID as varchar(100)) as varchar(100)) Hierarchy,
RecursionLevel + 1 AS RecursionLevel

FROM Recursive_CTE parent
INNER JOIN WBSStructures child ON child.ParentUnitID = parent.BusinessUnitID
)
SELECT * FROM Recursive_CTE ORDER BY Hierarchy
Related categories: SQL Microsoft SQL Server