为了账号安全,请及时绑定邮箱和手机立即绑定

一个sql存储过程循环遍历赋值的问题

一个sql存储过程循环遍历赋值的问题

Smart猫小萌 2018-12-06 17:24:56
要实现的效果是:如果传进去的@cyid=0,则把chengyuan表中所有成员的cyoffer 和cyreturn改变;如果传进去的@cyid!=0,且@cyid是chengyuan表中的成员id,则,改变当前id对应的cyoffer 和cyreturn值。 结算存储过程如下 ---------------------------成员结算----------------create proc sp_jiesuan@cyid int ,--要结算的成员id,如果id为零则将所有成员结算@jiesuane numeric(18,2)--结算额asset nocount on set rowcount 0set transaction isolation level read uncommitted declare @error_no integer, --错误号 @error_info varchar(255)---错误信息 select @error_no =0, @error_info ='' select @cyid=isnull(@cyid,0), @jiesuane =isnull(@jiesuane,0.00)begin transaction declare @yingfu numeric(18,2)if @cyid=0begindeclare @icy intselect @icy=1while @icy<=(select count(cyid) from chengyuan)begindeclare @id int select @id=(select top 1 cyid from chengyuan where cyid not in( select top (@icy-1) cyid from chengyuan order by cyid asc) order by cyid asc), @yingfu= ((select cyreturn from chengyuan where cyid=@id)-(select cyoffer from chengyuan where cyid=@id))if @yingfu>@jiesuaneupdate chengyuan set cyoffer=cyoffer+@jiesuane where cyid=@idelse if @yingfu=@jiesuaneupdate chengyuan set cyoffer=0 ,cyreturn=0 where cyid=@idelse if @yingfu<@jiesuaneupdate chengyuan set cyoffer=@jiesuane-@yingfu ,cyreturn=0 where cyid=@idset @icy=@icy+1endendelse --declare @icy1 int--select @icy1=1if @cyid in (select cyid from chengyuan)beginselect @yingfu=(select cyreturn from chengyuan where cyid=@cyid)-(select cyoffer from chengyuan where cyid=@cyid)if @yingfu>@jiesuaneupdate chengyuan set cyoffer=cyoffer+@jiesuane where cyid=@cyidelse if @yingfu=@jiesuaneupdate chengyuan set cyoffer=0 ,cyreturn=0 where cyid=@cyidelse if @yingfu<@jiesuaneupdate chengyuan set cyoffer=@jiesuane-@yingfu ,cyreturn=0 where cyid=@cyidendcommit transactionif @error_no!=0 return @error_noreturn 0 问题是:其中当@cyid=0时,为什么chengyuan表中cyid=1的那条数据没有改变,其他的数据均改变了?
查看完整描述

2 回答

?
UYOU

TA贡献1878条经验 获得超4个赞

你的语句需要修改 因为你在执行

select @id=(select top 1 cyid from chengyuan where cyid not in(
select top (@icy-1) cyid from chengyuan order by cyid asc) order by cyid asc),
@yingfu= ((select cyreturn from chengyuan where cyid=@id)-(select cyoffer from chengyuan where cyid=@id))

这一段的时候 第一次循环时@id在(select cyreturn from chengyuan where cyid=@id )里面为null值的

所以@yingfu 也等于null  当然后面的update语句@id才是第一次查询出来的值

等到第二次循环后在(select cyreturn from chengyuan where cyid = @id) @id等于第一次循环的值后面的update语句@id才是第二次查询出来的值

(注意:不管declare @icy int循环内还是循环前,值一样)

 

查看完整回答
反对 回复 2019-01-07
?
月关宝盒

TA贡献1772条经验 获得超5个赞

select 、update等SQL语句都是对行同时操作的。如一个表test(a,b)

a   b

1  2

update test set a=b,b=a where a=1后,

结果:

a  b

2  1

查看完整回答
反对 回复 2019-01-07
  • 2 回答
  • 0 关注
  • 1593 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信