22,209
社区成员
发帖
与我相关
我的任务
分享
create table hf
(Dept_code varchar(10),
parent varchar(10),
地点 varchar(10))
insert into hf
select '1', null, '中国' union all
select '100', '1', '广东' union all
select '101', '1', '安徽' union all
select '102', '1', '河南' union all
select '103', '1', '河北' union all
select '10001', '100', '深圳' union all
select '10002', '100', '广州' union all
select '1000101', '10001', '深圳A区' union all
select '1000102', '10001', '深圳B区'
;with t as
( select 1 leave,parent,地点,cast('' as varchar(10)) r from hf a
union all
select t.leave+1 leave,c.parent,t.地点 '地点',c.地点 r
from hf c
inner join t on c.Dept_code=t.parent
)
select f.Dept_code,f.parent,f.地点,g.paths '地点路径'
from hf f
inner join
(select d.地点,
stuff((select '/'+r from t e
where e.地点=d.地点
order by leave desc
for xml path('')),1,1,'')+d.地点 'paths'
from t d group by d.地点) g
on f.地点=g.地点
/*
Dept_code parent 地点 地点路径
---------- ---------- ---------- --------------------------
1 NULL 中国 中国
100 1 广东 中国/广东
101 1 安徽 中国/安徽
102 1 河南 中国/河南
103 1 河北 中国/河北
10001 100 深圳 中国/广东/深圳
10002 100 广州 中国/广东/广州
1000101 10001 深圳A区 中国/广东/深圳/深圳A区
1000102 10001 深圳B区 中国/广东/深圳/深圳B区
(9 row(s) affected)
*/