我在SQL Server 2008中使用T / SQL
我有一个包含以下列的表MyTable:
CHILD
PARENT
HIERARCHY
HIERARCHY列目前是空的,但我想填充它。
我有一些代码可以创建一个层次结构ID(改编自Recursive Child/Parent queries in T/SQL中的代码) 这段代码效果非常好。
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
)
我可以通过以下方式查看此查询的结果:
select CHILD,GENERATION,Hierarchy from n
但是我想将结果放回MyTable中的Hierarchy列中。 这段代码不起作用!
update MyTable e
set HIERARCHY='/'+(select hierarchy from n where n.CHILD=e.CHILD)
有谁知道怎么做?谢谢!
答案 0 :(得分:4)
也许是这样的:
;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
)
UPDATE MyTable
SET Hierarchy=n.hierarchy
FROM MyTable
JOIN n
ON n.CHILD=MyTable.CHILD
修改强>
你的意思是这样的:
;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
)
UPDATE MyTable
SET Hierarchy='/'+n.hierarchy+'/'
FROM MyTable e
JOIN n ON n.child=e.child