CREATE trigger monupdate
on daycheck
for insert,update,delete
as
set nocount onselect sum(cdcs) as cdcs,sum(ztcs) as ztcs,username,yearmonth 
into #t
from (
select cdcs,ztcs,username,yearmonth=convert(char(7),checkdate,120)
from inserted
union all
select -cdcs,-ztcs,username,yearmonth=convert(char(7),checkdate,120)
from deleted
) as t
group by username,yearmonthupdate monthcheck
 set cdcs=a.cdcs+t.cdcs,
     ztcs=a.ztcs+t.ztcs
from monthcheck a,#t t
where a.username=t.username
and a.yearmonth=t.yearmonthinsert monthcheck(cdcs,ztcs,username,yearmonth)
select cdcs,ztcs,username,yearmonth
from #t t
where not exists (
select 1 from monthcheck a
where a.username=t.username
and a.yearmonth=t.yearmonth
)go

解决方案 »

  1.   

    说明:
    1、应该加删除的情况,一起处理会简单明了些。
    2、不要用变量,用连接,这样可以处理一次插入、修改、删除多条记录的情况。
    3、月份取法你自己的可顶有问题,我上面的取的是2004-04,我觉得这样规范些,如果一定要2004-4,把yearmonth=convert(char(7),checkdate,120)改成yearmonth=cast(year(checkdate) as varchar(5))+'-'+cast(month(checkdate) as varchar(5))
      

  2.   


    create trigger monupdate on daycheck
    instead of insert,update
    as
    if exists(select 1 from deleted)
    update daycheck 
    set username=b.username,checkdate=b.checkdate
    ,cdcs=b.cdcs,ztcs=b.ztcs
    from daycheck a join(
    select a.id,a.username,checkdate
    ,case when b.username is null then cdcs+3 else cdcs end
    ,case when b.username is null then ztcs+1 else ztcs end
    from inserted a left join monthcheck b 
    on a.username=b.username
    and datediff(month,a.checkdate,b.yearmonth)=0
    )b on a.id=b.id
    else
    insert daycheck(username,checkdate,cdcs,ztcs)
    select a.username,checkdate
    ,case when b.username is null then cdcs+3 else cdcs end
    ,case when b.username is null then ztcs+1 else ztcs end
    from inserted a left join monthcheck b 
    on a.username=b.username
    and datediff(month,a.checkdate,b.yearmonth)=0insert monthcheck(username,yearmonth,cdcs,ztcs)
    select a.username,convert(char(7),a.checkdate,120),a.cdcs,a.ztcs
    from inserted a left join monthcheck b 
    on a.username=b.username
    and datediff(month,a.checkdate,b.yearmonth)=0
    where b.username is null 
    go