I have two tables: my_table1
and my_table2
. a_column in my_table2
should always match the corresponding value in my_table1
.
However, the tricky part is that rows in my_table2
may be inserted before or after the corresponding row in my_table1.
I’ve tried to handle this using triggers, but it's not working as expected. Here's what I have so far:
CREATE OR REPLACE FUNCTION trig_get_column_data() RETURNS trigger AS
$$
BEGIN
SELECT a_column
FROM my_table1
WHERE (a, b) = (new.a, new.b)
INTO new.column;
RETURN new;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE TRIGGER get_column_data
BEFORE INSERT OR UPDATE
ON my_table2
FOR EACH ROW
WHEN ( new.a_column ISNULL OR TRIM( BOTH new.a_column ) = '')
EXECUTE PROCEDURE trig_get_column_data();
CREATE OR REPLACE FUNCTION trig_aft_ins() RETURNS trigger AS
$$
BEGIN
UPDATE my_table2 t
SET a_column = o.a_column
FROM new_datas o
WHERE (t.a, t.b) = (o.a, o.b);
RETURN new;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trig_aft_ins
AFTER INSERT
ON my_table1
REFERENCING new TABLE AS new_datas
FOR EACH STATEMENT
EXECUTE PROCEDURE trig_aft_ins( )
The issue I'm facing is that sometimes the a_column in my_table2
doesn't get updated when the corresponding row in my_table1
is inserted later. How can I ensure that a_column in my_table2
always reflects the correct value from my_table1
, regardless of which row gets inserted first?
Any help or better approach is appreciated!
column
which is a reserved keyword, throwing a syntax error on call of your trigger?