一个循环算法的问题 长长的标题 请大家帮忙~~~ 谢谢

tojht tojht 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
表tb
id yc ym begin end month code
101 100.00 120.00 150.00 130.00 1 1
101 130.00 30.00 130.00 230.00 2 1
501 1 2 5 4 1 1
501 2 3 4 3 2 1
501 5 7 12 10 1 9999
20201 13 12 10 9 1 1100



就是这样一个余额表 除了1月的Begin已经有数据外 其他月的BEGIN 都等于上一个月的END 例如 2月的BEGIN=1月的END , 而 以1开头或者5开头的ID 他的END =BEGIN +YC - YM ,2 3 4开头的ID 他的END = BEGIN +YM-YC 每条数据都有12个月 。。。 算出所有数据的BEGIN 和END。。。。(CODE是上一级的单位 编号可能相同 但是上一级单位不同)

这是我写的算法 要循环9999次 好慢呀 !!!!
DECLARE @code INT,
@id varchar(100),
@begin numeric(18,2),
@mon int
set @mon=1
SET @code=1
WHILE (@code<=9999)
begin
DECLARE A1 CURSOR FOR
SELECT id FROM tb WHERE code=@code GROUP BY id
OPEN A1
FETCH NEXT FROM A1 INTO @id
WHILE @@FETCH_STATUS=0
begin

while @mon<=12
BEGIN
if(@id like '1%' or @id like '5%')
begin
select @begin=isnull(begin,0)+isnull(yc,0)-isnull(ym,0) from tb where id=@id and code=@code and month=@mon
update tb set end=@begin where id=@id and code=@code and month=@mon
update tb set begin=@begin where month=@mon+1 and code=@code and id=@id
set @begin=0
set @mon=@mon+1
end
else
begin
select @begin=isnull(begin,0)+isnull(ym,0)-isnull(yc,0) from tb where id=@id and code=@code and month=@mon
update tb set end=@begin where month=@mon and code=@code and id=@id
update aly_accsum set mbeginbal=@begin where month=@mon+1 and code=@code and id=@id
set @ycye=0
set @mon=@mon+1
end

END

FETCH NEXT FROM A1 INTO @id
set @mon=1
end
close A1
deallocate A1
set @code=@code+1
end


所以 请教高手 怎么写才快一些? 我是新人 如果可以的话 把您写的代码 加上一些注释 谢谢各位大大。。。。~
...全文
评论 10
收藏 已收藏
分享
返回顶部
tojht
疑难问题 22,299 成员 121,727 内容