CREATE TABLE emp (
empname text NOT NULL,
salary integer
);
CREATE TABLE emp_audit(
operation text NOT NULL,
stamp timestamp NOT NULL,
userid text NOT NULL,
empname text NOT NULL,
salary integer
);
创建存储过程:
CREATE OR REPLACE FUNCTION process_emp_audit()
RETURNS TRIGGER AS
$emp_audit$
BEGIN
IF (TG_OP = 'DELETE') THEN
INSERT INTO emp_audit SELECT 'DELETE',now(),user,OLD.*;
ELSIF (TG_OP = 'UPDATE') THEN
-- save old and new values
INSERT INTO emp_audit SELECT 'OLD',OLD.*;
INSERT INTO emp_audit SELECT 'NEW',NEW.*;
ELSIF (TG_OP = 'INSERT') THEN
INSERT INTO emp_audit SELECT 'INSERT',NEW.*;
ELSEIF (TG_OP = 'TRUNCATE') THEN
INSERT INTO emp_audit SELECT 'TRUNCATE','-',-1;
END IF;
RETURN NULL; -- result is ignored bacause this is an AFTER trigger
END;
$emp_audit$ LANGUAGE plpgsql;
创建针对insert和update每行的触发器:
AFTER INSERT OR UPDATE OR DELETE ON emp
FOR EACH ROW EXECUTE PROCEDURE process_emp_audit();
创建针对update的语句级的触发器:
CREATE TRIGGER emp_audit_truncate AFTER TRUNCATE ON emp FOR EACH STATEMENT EXECUTE PROCEDURE process_emp_audit(); 原文链接:https://www.f2er.com/postgresql/195702.html