表有3列:单位编号、级次、上级单位:
dwbh jc sjdw
00 1
01 2 00
0101 3 01
0102 3 01
02 2 00
0201 3 02
0202 3 02
020201 4 0202
020202 4 0202
现在要查询任意一个单位编号的所有下级单位,如查询02 的所有下级单位。求解决方案
------解决方案--------------------
create table #a(dwbh varchar(10) ,jc int ,sjdw varchar(10))
insert into #a values('00',1,null),('01',2,'00'),('0101',3,'01'),('0102',3,'01'),('02',2,'00')
,('0201', 3 ,'02'),('0202', 3 ,'02'),('020201', 4 ,'0202'),('020202', 4 ,'0202')
;with _a as (
select * from #a where dwbh = '02'
union all
select a.* from #a a
join _a b on a.sjdw = b.dwbh
)
select * from _a
drop table #a
--------------------------------------------------------------
dwbh jc sjdw
02 2 00
0201 3 02
0202 3 02
020201 4 0202
020202 4 0202