目录
- 构造表与数据
drop table if exists ta;
drop table if exists tb;
create table ta(id int, name varchar);
create table tb(id int);
insert into ta select n, n || 'name' from generate_series(1, 100, 1) as t(n);
- 创建触发器与触发器函数
CREATE OR REPLACE FUNCTION func_sum_max_id_to_tb()
RETURNS TRIGGER
AS
$BODY$
DECLARE
BEGIN
insert into tb select max(id) from ta;
raise notice 'hello ';
RETURN NULL;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER;
create trigger trg_ta after insert or delete or update on ta for each STATEMENT EXECUTE PROCEDURE func_sum_max_id_to_tb();
-
测试语句级别触发器
-
删除之前
select * from ta where id<11;
- 结果:
- 删除之后
delete from ta where id<11;
- 查看表tb
select * from tb;
- 结果
- 可见,在使用语句级别触发器的时候,即使删除了10条记录,但是只触发了一次触发器