Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql, how to add multiple table for one trigger

I have a question: how to add multiple table for one trigger? Is that possible, or should I just make another 2 triggers for 2 different tables?

like image 385
R0ck99 Avatar asked May 07 '26 06:05

R0ck99


1 Answers

Create a new function

CREATE OR REPLACE FUNCTION updated_timestamp_func()
RETURNS TRIGGER
LANGUAGE plpgsql AS
'
BEGIN
    NEW.updated_at = now();
    RETURN NEW;
END;
';

Then create a trigger for each table that has the column updated_at

DO $$
DECLARE
    t text;
BEGIN
    FOR t IN
        SELECT table_name FROM information_schema.columns WHERE column_name = 'updated_at'
    LOOP
        EXECUTE format('CREATE TRIGGER trigger_update_timestamp
                    BEFORE UPDATE ON %I
                    FOR EACH ROW EXECUTE PROCEDURE updated_timestamp_func()', t,t);
    END loop;
END;
$$ language 'plpgsql';
like image 86
abbas Avatar answered May 10 '26 23:05

abbas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!