日期:2014-05-17 浏览次数:20551 次
--触发器是不需要你操作的,当你执行新增,更新,删除时自动调用的,给你举个例子
if object_id('t1') is not null drop table t1
if object_id('t2') is not null drop table t2
if object_id('t3') is not null drop table t3
create table t1(id int primary key,a int not null)
create table t2(id int primary key,a int not null)
create table t3(id int primary key,a int not null)
go
create trigger t1_trg
on t1
for insert,update,delete
as
--新增,更新
if exists(select 1 from inserted)
begin
update t3 set a=t1.a+isnull(t2.a,0)
from inserted i
inner join t1 on i.id=t1.id
left join t2 on i.id=t2.id
where i.id=t1.id and i.id=t3.id
insert into t3
select t1.id,t1.a+isnull(t2.a,0)
from inserted i
inner join t1 on i.id=t1.id
left join t2 on i.id=t2.id
where not exists(select 1 from t3 where i.id=t3.id)
end
--删除
if exists(select 1 from deleted)
and not exists (select 1 from inserted)
begin
update t3 set a=t1.a+isnull(t2.a,0)
from inserted i
inner join t1 on i.id=t1.id
left join t2 on i.id=t2.id
where i.id=t3.id
delete t3
from deleted d
where t3.id=d.id
and not exists(select 1 from t1 where t1.id=t3.id and t1.id=d.id)
and not exists(select 1 from t2 where t2.id=t3.id and t2.id =d.id)
end
go
create trigger t2_trg
on t2
for insert,update,delete
as
--新增,更新
if exists(select 1 from inserted)
begin
update t3 set a=t2.a+isnull(t1.a,0)
from inserted i
inner join t2 on i.id=t2.id
left join t1 on i.id=t1.id
where i.id=t2.id and i.id=t3.id
insert into t3
select t2.id,t2.a+isnull(t1.a,0)
from inserted i
inner join t2 on i.id=t2.id
left join t1 on i.id=t1.id
where not exists(select 1 from t3 where i.id=t3.id)
end
--删除
if exists(select 1 from deleted)
and not exists (select 1 from inserted)
begin
update t3 set a=t2.a+isnull(t1.a,0)
from inserted i
inner join t2 on i.id=t2.id
left join t1 on i.id=t1.id
where i.id=t3.id
delete t3
from deleted d
where t3.id=d.id
and not exists(select 1 from t1 where t1.id=t3.id and t1.id=d.id)
and not exists(select 1 from t2 where t2.id=t3.id and t2.id =d.id)
end
go