--没经过测试。create trigger tr_table1 on table1
for insert,update,delete
as
insert into table2(d,c)
select a+b,c from inserted
where not exists(select 1 from deleted)update table2
set d=a+b,
c=i.c
from inserted i,deleted d
where table2.c=d.c and i.c <>d.cdelete table2 from table2
inner join deleted d on table2.c=d.c
where not exists(select 1 from inserted) and exists(select 1 from deleted)

解决方案 »

  1.   

    create table table1(a int,b int,c int)
    create table table2(b int,c int)
    insert table1
    select 2,6,2 select * from table1
    select * from table2
    --truncate table table1
    --truncate table table2
    --drop table table1
    create trigger test_tr on table1
    for insert,update,delete
    as
    if not exists(select 1 from table2,inserted where table2.c=inserted.c)
    insert table2
    select a+b,c
    from inserted
    else
    begin 
    update a
    set a.b=a.b+i.a+i.b
    from table2 a inner join inserted i on a.c=i.c
    update a 
    set a.b=a.b-d.a-d.b
    from table2 a inner join deleted d on a.c=d.c
    end
    已测试通过,楼主测试一下
      

  2.   

    alter trigger test_tr on table1
    for insert,update,delete
    as
    if not exists(select 1 from table2,inserted where table2.c=inserted.c)
    insert table2
    select a+b,c
    from inserted
    else
    update a
    set a.b=a.b+i.a+i.b
    from table2 a inner join inserted i on a.c=i.c
    update a 
    set a.b=a.b-d.a-d.b
    from table2 a inner join deleted d on a.c=d.c
    这样就完美了