日期:2014-05-19  浏览次数:20507 次

请教有点难的SQL语句
表1   d_ry
gh   char(8)   工号   主键
sjldgh   char(8)   上级领导工号
name   varchar(10)

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

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

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

------解决方案--------------------
select * form d_ywy where gh in (select gh from d_ry where sjldgh=@sjldgh)
这句只查出一层,一般来说都会定下来有几层,如果没定下来的话,业务太复杂,一句就很难解决,得要写个存储过程了
------解决方案--------------------
路过。。。
------解决方案--------------------
知道了,==你试试的
select gh from (select gh from (select gh from a.gh=b.sjldgh) as a)as b)
------解决方案--------------------
CREATE PROCEDURE aa
@sjldgh char(10)
AS
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
GO
累啊,给分吧