create table tb1(a int ,b int ,c int ,d int)--a is the primary key
go
create table tb2(b int ,c int, d int)
go
create trigger t_insert on tb1
for insert
as
set nocount on
insert into tb2(b,c,d) select distinct b,c,d from inserted t
where not exists (select 1 from tb2 where a=t.a and b=t.b and c=t.c and d=t.d)
set nocount off
go
insert into tb1 values(1,1,2,3)
insert into tb1 values(2,1,2,3)
insert into tb1 values(3,3,3,4)
insert into tb1 values(4,4,4,5)
go
select * from tb1
/*
a b c d
1 1 2 3
2 1 2 3
3 3 3 4
4 4 4 5
*/
select * from tb2
/*
b c d
1 2 3
3 3 4
4 4 5
*/
go
create trigger t_update on tb1 for update
as
set nocount on
if exists (select 1 from tb1 inner join deleted d
on tb1.b=d.b and tb1.c=d.c and tb1.d=d.d
where tb1.a<>d.a)
begin
insert into tb2(b,c,d) select distinct i.b,i.c,i.d from inserted i
where
not exists
(
select 1 from
(select tb2.* from tb2
inner join deleted d
on tb2.b=d.b
and tb2.c=d.c
and tb2.d=d.d) x
where x.b=i.b
and x.c=i.c
and x.d=i.d
)
end
else
update tb2 set b=i.b,c=i.c,d=i.d
from tb2 inner join deleted d
on tb2.b=d.b and tb2.c=d.c and tb2.d=d.d
inner join inserted i
on i.a=d.a
set nocount off
go
update tb1 set c=100 where a=2--insert
go
select * from tb2
/*
b c d
1 2 3
3 3 4
4 4 5
1 100 3
*/
go
update tb1 set c=100 where a=3--update
go
select * from tb2
/*
b c d
1 2 3
3 100 4
4 4 5
1 100 3
*/
go
drop table tb1,tb2