Fire trigger on update of columnA or ColumnB or ColumnC

后端 未结 3 804
旧时难觅i
旧时难觅i 2020-12-28 16:38

I have the code to fire a trigger only on an update of a single specific column. The trigger is used to fire a function that will raise a postgres \"notify\" event, which I

3条回答
  •  天命终不由人
    2020-12-28 17:05

    The above solutions were not working for me properly. So after reading through documentation again. I found few things to take note of. BEFORE UPDATE ON - AFTER UPDATE ON triggers are executed differently. Since my procedure was returning the NEW record with updated value. It was not working in AFTER trigger and in BEFORE trigger, the OR statements inside WHEN clause needed to be enclosed by braces.

    CREATE TRIGGER check_update
    BEFORE UPDATE ON some_table
    FOR EACH ROW
    WHEN ((OLD.colum_name_1 IS DISTINCT FROM NEW.colum_name_1) OR (OLD.colum_name_2 IS DISTINCT FROM NEW.colum_name_2))
    EXECUTE PROCEDURE update_updated_at_column();
    

    And the procedure

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

提交回复
热议问题