大力等高手,以变量为条件更新的更新语句

cgq214 2005-05-26 09:55:55
tb 表结构
rID rLastQty

1 3
2 2
3 5
4 6

declare @Num decimal(18,4) --中间变量
set @Num=6

--先进先出算法
declare @j decimal(18,4) --中间变量
set @j=0
update tb set @j=case when @num>rLastQty then rLastQty else @num end ,
rLastQty=rLastQty - @j,@num=@num-@j

问题1:如何实现 当@num=0的时候就不更新了,逻辑上面讲就是tb表3+2+5 > 6以后的记录就不更新了
上面的tb表将rlastQty为3,2,5更新为0,0,4,而后面的记录不执行更新

问题2:如何 取出累计大于@Num=6的前面记录,就是tb表的前三条记录,3+2+5>6
类似 select * from tb where sum(rLastQty)>6
...全文
106 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
cgq214 2005-05-26
  • 打赏
  • 举报
回复
to: zjcxc(邹建)
问题1,我所希望的是:(所影响的行数为 3 行)而不是全部记录4行,
因为数据量10w左右的话,性能会有影响
zjcxc 2005-05-26
  • 打赏
  • 举报
回复
--示例数据
create table tb(rID int,rLastQty int)
insert tb select 1,3
union all select 2,2
union all select 3,5
union all select 4,6
go

declare @Num decimal(18,4) --中间变量
set @Num=6

--问题2
select * from tb
where isnull((select sum(rLastQty) from tb a where a.rID<tb.rID),0)<@Num

--问题1
--先进先出算法union all select
declare @j decimal(18,4) --中间变量
update tb set
@j=case when @num>rLastQty then rLastQty else @num end,
@num=@num-@j,
rLastQty=rLastQty-@j
where isnull((select sum(rLastQty) from tb a where a.rID<tb.rID),0)<@Num
select * from tb
go

--删除测试
drop table tb

/*--结果
rID rLastQty
----------- -----------
1 3
2 2
3 5

(所影响的行数为 3 行)


rID rLastQty
----------- -----------
1 0
2 0
3 4
4 6

(所影响的行数为 4 行)
--*/

spring_504 2005-05-26
  • 打赏
  • 举报
回复
1,while(@num>0)
begin
update tb set @j=case when @num>rLastQty then rLastQty else @num end ,
rLastQty=rLastQty - @j,@num=@num-@j
end
2,select * from tb where rID in(select rID from tb where sum(rLastQty)>6
)
zjcxc 2005-05-26
  • 打赏
  • 举报
回复
晕,你注意看了么? 最后那个影响行数是给你显示更新结果时的查询影响行数,不是更新影响行数.

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧