获取树型节点的全名称

-- 获取树型节点的全名称:父节点名称 + ... + 当前节点名称
with test(fid, fname, fparentid) as (
-- 结果1, 见附图
values('01', 'test01', '0')
union
values('0101', 'test0101', '01')
union
values('010101', 'test010101', '0101')
union
values('0102', 'test0102', '01')
union
values('02', 'test02', '0')

),
temp(fid, fname, fparentid) as (
--由于连接后的名称比较长,所以需要增加varchar的长度
select fid, cast( fname as varchar(100) ), fparentid from test -- where 条件
union all
select child.fid, cast( parent.fname||'/'||child.fname as varchar(100) ), parent.fparentid from temp as child, test as parent where child.fparentid = parent.fid
)
-- 结果3, 见附图
select t.fid, t.fname, test.fparentid from (
-- 结果2(没有过滤fparentid = '0'时), 见附图
select fid, fname, fparentid from temp where fparentid = '0' order by fid
) as t, test where t.fid = test.fid

你可能感兴趣的:(db2)