日期:2014-05-18  浏览次数:20512 次

帮个忙呗。实在不会了
表1   d_ry
gh   char   工号   主键
sjldgh   char   上级领导工号
name   varchar(10)

表2   d_ywy
ywdh   char(10)业务单号   主键
ywje   decimal(9,2)   业务金额
gh   char   工号

其中业务员是树状分布,即通过表1知道其上级人员的工号这样串起来

想求任意给定的工号人号,及其所有下属的业务单号,业务金额的明细
下属是指其下级或下级的下级这样的,直到叶




------解决方案--------------------
declare @sjldgh char
select @sjldgh = 'B '

create table #temp
(gh char)

insert into #temp
select gh from d_ry where sjldgh = @sjldgh

while exists (select gh from d_ry x
where sjldgh in (select gh from #temp)
and not exists (select * from #temp y where y.gh = x.gh)
)
begin
insert into #temp
select gh from d_ry x
where sjldgh in (select gh from #temp)
and not exists (select * from #temp y where y.gh = x.gh)
end

select * from #temp

select x.ywdh, x.ywje, y.gh
from d_ywy x,
#temp y
where x.gh = y.gh

drop table #temp