Update a table with a trigger after update

后端 未结 3 2039
礼貌的吻别
礼貌的吻别 2020-12-21 09:36

I have two tables

 batch (batch_id,start_date,end_date,batch_strength,is_locked)
 sem (user_id,is_active,no_of_days)

I have executed the tr

3条回答
  •  一个人的身影
    2020-12-21 09:59

    Infinite recursion in this case because update trigger will do update operation on table batch and the same will triggered after execution of update statement inside em_sem_batch trigger itself.To prevent this add one column in table and in update statement of trigger update that column also to some value and add an if condition to check whether that column has that constant value if so avoid execution of update statement else execute update statement. See example below:

    CREATE FUNCTION public.trigger_fuction()
        RETURNS trigger
        LANGUAGE 'plpgsql'
        NOT LEAKPROOF
    AS $BODY$
    BEGIN
      IF NEW.data_replicated=true THEN
        UPDATE sample SET data_replicated=false WHERE id=NEW.id;
        raise notice 'changed data replicated of sample with id as %',NEW.ID;
      END IF;
      RETURN NEW;
    END;
    $BODY$;
    
    
    CREATE TRIGGER data_replication_trigger
      AFTER UPDATE
      ON sample
      FOR EACH ROW
      EXECUTE PROCEDURE trigger_fuction();
    

    In this example sample table has data_replicated boolean field which will be updated when trigger is executed.

提交回复
热议问题