I am using T/SQL in SQL Server 2008
I have a table MyTable with the following columns:
CHILD
PARENT
HIERARCHY
The HIERARCHY column is currently empty, but I would like to populate it.
I have some code which creates a hierarchy ID (adapted from the code in Recursive Child/Parent queries in T/SQL)
This code works very nicely.
with n(CHILD, PARENT, GENERATION, hierarchy) as (
select CHILD, PARENT,0, CAST(CHILD as nvarchar) as GENERATION from MyTable
where PARENT=1
union all
select nplus1.CHILD, nplus1.PARENT, GENERATION+1,
cast(n.hierarchy + '/' + CAST(nplus1.CHILD as nvarchar) as nvarchar)
from
MyTable nplus1 inner join n on nplus1.PARENT=n.CHILD and
)
I can see the results of this query by doing:
select CHILD,GENERATION,Hierarchy from n
However I would like to put the result back in the column Hierarchy in MyTable.
This code does not work!
update MyTable e
set HIERARCHY='/'+(select hierarchy from n where n.CHILD=e.CHILD)
Does anyone know how to do it? Thank you!
Maybe something like this:
Edit
You mean like this: