日期:2014-05-17  浏览次数:20533 次

数据补差问题
数据补差 怎么可以不写循环 用复合sql语句实现?请将下面cursor转换为复合sql语句
--补差
declare @zlyje decimal(12,2),@zhyje decimal(12,2),@lyje decimal(12,2),@hyje decimal(12,2),@ymclcode char(12),@ph varchar(60)
declare @ymcljglb char(8),@ymclflcode char(12)

declare hyje_cursor insensitive cursor for select distinct cljglb,clflcode from #cpcbhy_ymmxz_hz where cjdw=@cjdw and hsyear=2013 and hsmonth=7
open hyje_cursor
fetch next from hyje_cursor into @ymcljglb,@ymclflcode
while @@fetch_status=0
begin
select @zlyje=lyje from #cbsj where cljglb=@ymcljglb and clflcode=@ymclflcode
select @lyje=sum(lyje),@hyje=SUM(hyje) from #cpcbhy_ymmxz_hz where cjdw=@cjdw and hsyear=2013 and hsmonth=7 and cljglb=@ymcljglb and clflcode=@ymclflcode

select top 1 @ymclcode=clcode,@ph=ph from #cpcbhy_ymmxz_hz where cjdw=@cjdw and hsyear=2013 and hsmonth=7 and cljglb=@ymcljglb and clflcode=@ymclflcode
order by lysl desc

update #cpcbhy_ymmxz_hz set lyje=lyje +@zlyje - @lyje where cjdw=@cjdw and hsyear=2013 and hsmonth=7 and cljglb=@ymcljglb and clflcode=@ymclflcode and
clcode=@ymclcode and ph=@ph
fetch next from hyje_cursor into @ymcljglb,@ymclflcode
end
close hyje_cursor
deallocate hyje_cursor

------解决方案--------------------
--create table #zsj(xb char(2),sl  decimal(12,2) not null default 0)
 
-- insert into #zsj(xb,sl) values ('男',10)
--  insert into #zsj(xb,sl) values ('女',15)

-- create table #b1(xb char(2),rm char(12),sl decimal(12,2) not null default 0)
-- insert into #b1(xb,rm,sl)values('男','张三',3.3)
-- insert into #b1(xb,rm,sl)values('男','李四',3.3)
-- insert into #b1(xb,rm,sl)values('男','王五',3.3)
 
-- insert into #b1(xb,rm,sl)values('女','赵六',3.2)
-- insert into #b1(xb,rm,sl)values('女','钱七',5.7)
-- insert into #b1(xb,rm,sl)values('女','孙八',5.3)

-- declare @sl decimal(12,2),@zsl decimal(12,2),@rm char(12),@xb char(2)
-- declare hyje_cursor insensitive cursor for select  xb,sl from #zsj 
--open hyje_cursor
--fetch next from hyje_cursor into @xb,@zsl
--while @@fetch_status=0
--begin

--select @sl=sum(sl) from #b1 where xb=@xb

--select top 1 @rm=rm  from #b1 where xb=@xb  order by rm  

--update #b1 set sl=sl +@zsl - @sl where xb=@xb and rm=@rm 

--fetch next from hyje_cursor into @xb,@zsl<