jueves, 25 de febrero de 2021

PostgreSQL Trigger INSERT, UPDATE and DELETE

 

CREATE TABLE emp (
    empname           text NOT NULL,
    salary            integer
);

CREATE TABLE emp_audit(
    operation         char(1)   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
        --
        -- Create a row in emp_audit to reflect the operation performed on emp,
        -- making use of the special variable TG_OP to work out the operation.
        --
        IF (TG_OP = 'DELETE') THEN
            INSERT INTO emp_audit SELECT 'D', now(), user, OLD.*;
        ELSIF (TG_OP = 'UPDATE') THEN
            INSERT INTO emp_audit SELECT 'U', now(), user, NEW.*;
        ELSIF (TG_OP = 'INSERT') THEN
            INSERT INTO emp_audit SELECT 'I', now(), user, NEW.*;
        END IF;
        RETURN NULL; -- result is ignored since this is an AFTER trigger
    END;
$emp_audit$ LANGUAGE plpgsql;

CREATE TRIGGER emp_audit
AFTER INSERT OR UPDATE OR DELETE ON emp
    FOR EACH ROW EXECUTE FUNCTION process_emp_audit();
 
Fuente:
https://www.postgresql.org/docs/12/plpgsql-trigger.html 
 

1 comentario:

  1. Mohegan Sun Arena at Casey Plaza Tickets - JTM Hub
    Buy Mohegan Sun Arena at Casey Plaza tickets at JTMHub. 김천 출장샵 Find Mohegan Sun Arena at Casey Plaza venue 전주 출장안마 concert and event schedules, Feb 10, 2022John Fogerty Concert at Mohegan SunFeb 18, 안양 출장샵 2022Gordy String Quartet at Mohegan SunFeb 19, 2022Shinedown at Casey 양주 출장샵 Plaza 상주 출장안마

    ResponderEliminar