I have a table a
with 3 triggers that insert, update, or delete corresponding rows in b
whenever a row in a
is inserted, updated, or deleted. All 3 triggers use the same trigger function p
.
CREATE OR REPLACE FUNCTION p ()
RETURNS TRIGGER
AS $$
BEGIN
IF (TG_OP = 'INSERT') THEN
-- INSERT INTO b ...
RETURN NEW;
ELSIF (TG_OP = 'UPDATE') THEN
-- UPDATE b ...
RETURN NEW;
ELSIF (TG_OP = 'DELETE') THEN
-- DELETE FROM b ...
RETURN NEW;
ELSE
RETURN NULL;
END IF;
END;
$$ LANGUAGE PLPGSQL;
CREATE TRIGGER i AFTER INSERT ON a FOR EACH ROW EXECUTE PROCEDURE p ();
CREATE TRIGGER u AFTER UPDATE ON a FOR EACH ROW EXECUTE PROCEDURE p ();
CREATE TRIGGER d AFTER DELETE ON a FOR EACH ROW EXECUTE PROCEDURE p ();
a
also has a foreign key a1
into c
(with primary key c1
), and I would like to alter p
in such a way that it enters the IF
/ELSIF
branches also depending on a column c2
in c
: if that joined column changed, enter the INSERT
and UPDATE
branches; if it stayed the same, enter the UPDATE
branch. In effect, something like this:
IF (TG_OP = 'INSERT') OR ((TG_OP = 'UPDATE') AND (oldC.c2 <> newC.c2)) THEN
-- ...
ELSIF (TG_OP = 'UPDATE') OR (oldC.c2 = newC.c2) THEN
-- ...
ELSIF (TG_OP = 'DELETE') OR ((TG_OP = 'UPDATE') AND (oldC.c2 <> newC.c2)) THEN
-- ...
ELSE
-- ...
END IF;
where oldC
and newC
would result from joins similar to these (with approx. syntax):
SELECT oldC.* FROM a, c AS oldC WHERE OLD.a1 = c.c1;
SELECT newC.* FROM a, c AS newC WHERE NEW.a1 = c.c1;
So what is needed in effect are two joins outside the IF
statement, which would allow it to refer to oldC
and newC
(or something analogous). Is this possible and how would the altered version of p
look (with correct PostgreSQL syntax)?