![](https://i-blog.csdnimg.cn/blog_migrate/ab91cd0e9448f841eb09950ac6b54164.jpeg)
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
在单据保存后,自动给每种项目的累计列赋 上月25-本单据日期数据的累计值。
*/
alter proc [dbo].[ww_zhbb_sczhrbb_bch]
@voucherno varchar(60), --:单据类型,
@keyid varchar(60), --:单据ID,
@state varchar(60) --:状态[add、edit]
--@voucherno:单据类型,@keyid:单据ID,@state:状态[add、edit]
AS
BEGIN
if(@voucherno = 'ww_zhbb_sczhrbb')
begin
declare
@djrq varchar(100), --单据日期
@syrq varchar(100), --上月日期
@xyrq varchar(100), --下月日期
@djny varchar(100) --单据年月
/* 获取单据上月,下月,当前月的年月部分 */
select @djrq=convert(varchar(10),ddate,23) from ww_zhbb_sczhrbb where ID=@keyid
set @syrq=convert(varchar(7),DateAdd(month,-1,@djrq),23) --当前单据日期-1月,只取年月部分,形式为:2019-06
set @xyrq=convert(varchar(7),DateAdd(month,1,@djrq),23) --当前单据日期+1月,只取年月部分
set @djny=convert(varchar(7),@djrq,23) --当前单据日期,只取年月部分
--定义变量
declare @i int,
@ljsbyzl decimal(18,6),
@ljtc decimal(18,6),
@ljscsj decimal(18,6),
@ljcl decimal(18,6)
--循环
set @i = 1
while (@i<11)
begin
/*
若 当前日期的日<=24,取本单据所在月份 的上月25 - 该单据日期的数据汇总,
否则... 取 ... 本月25 - 该单据日期的数据汇总
*/
select @ljsbyzl=brsbyzl,@ljtc=brtc,@ljscsj=brscsj,@ljcl=brcl from
(select row_number() over (order by c.ww_zhbb_sczhrbbmx0_sortno) as RowID,sum(c.brsbyzl) AS brsbyzl,SUM(c.brtc)AS brtc,SUM(c.brscsj)AS brscsj,SUM(c.brcl)AS brcl
from ww_zhbb_sczhrbb as z left join ww_zhbb_sczhrbbmx0 as c on z.id = c.ww_zhbb_sczhrbbmx0_id
where (z.ddate >= Convert(date,(case when DAY(@djrq)<=24 then @syrq+'-'+'25' else @djny+'-'+'25' end)) and z.ddate <=@djrq) --到本单据日期为截至期限的写法
--Convert(date,(case when DAY(z.ddate)<=24 then @djny+'-'+'24' else @xyrq+'-'+'24' end)) -- 至本月24日或下月24为截至期限的数据累计 写法
group by c.ww_zhbb_sczhrbbmx0_sortno) as A WHERE RowID=@i
--SELECT @ljsbyzl,@ljtc,@ljscsj,@ljcl
update ww_zhbb_sczhrbbmx0 set ljsbyzl=@ljsbyzl,ljtc=@ljtc, ljscsj=@ljscsj, ljcl=@ljcl
where ww_zhbb_sczhrbbmx0_id = @keyid and ww_zhbb_sczhrbbmx0_sortno =@i*10
set @i = @i+1
end
end
END
GO