您正在寻找该REFERENCING new row as ... | old row as ...
子句。有关这方面的详细信息,请参阅参考文档。
一个简单的例子:
表设置
create table one (ID int primary key, F2 nvarchar(100));
create table two (ID int primary key, F2 nvarchar(100));
insert into one values (1, 'Bla');
insert into one values (2, 'Blupp');
insert into two values (1, 'Bla');
insert into two values (2, 'Blupp');
创建触发器
create trigger "ONE_TO_TWO"
after update
on "ONE"
referencing new row as new, old row as old
for each row
begin
update "TWO" t
set "F2" = :new."F2"
where t."ID" = :old."ID";
end;
检查当前数据
select
one.id as ONE_ID, one.f2 as ONE_F2
, two.id as TWO_ID, two.f2 as TWO_F2
from
one full outer join two
on one.id = two.id;
/*
ONE_ID ONE_F2 TWO_ID TWO_F2
1 Bla 1 Bla
2 Blupp 2 Blupp
*/
更新记录并再次检查数据
update "ONE"
set "F2" = 'CHANGED THIS'
where "ID" = 1;
/*
ONE_ID ONE_F2 TWO_ID TWO_F2
1 CHANGED THIS 1 CHANGED THIS
2 Blupp 2 Blupp
*/
虽然使用触发器通常看起来是一种好方法,但我建议重新考虑它的用途以及是否有更好的方法来处理需求。触发器本身总是在数据模型中引入“魔法”,因为它们改变了普通语句的语义——你UPDATE
突然更新了多个表——对数据库用户来说并不明显。事实上,只有积极寻找触发器,才有可能了解它们对数据库“行为”方式的影响。
对于多表更新,处理依赖关系的存储过程可能是实现目标的更明显和更好维护的方式。