Postgres insert or update trigger WHEN condition (old)

前端 未结 2 1545
北恋
北恋 2021-01-11 12:17

I need write insert or update trigger, but with WHEN condition with compare OLD and NEW rows.

According documentation OLD is null for insert operation. How i can use

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-11 12:24

    Option A:

    You can change the code so that conditions will be in the trigger function rather than the trigger itself. With this approach OLD will be used only in the UPDATE.

    Trigger:

    CREATE TRIGGER mytrigger
        BEFORE INSERT OR UPDATE ON "mytable"
        FOR EACH ROW 
        EXECUTE PROCEDURE mytrigger();
    

    Trigger function:

    CREATE OR REPLACE FUNCTION mytrigger()
      RETURNS trigger AS
    $BODY$
    begin
    if NEW.score > 0 then
         --code for Insert
         if  (TG_OP = 'INSERT') then
               YOUR CODE
         end if;
    
         --code for update
         if  (TG_OP = 'UPDATE') then
               if OLD.score <> NEW.score then  -- (if score can be null see @voytech comment to this post)
                  YOUR CODE
               end if;
         end if;
    end if;
    return new;
    end;
    $BODY$
      LANGUAGE plpgsql VOLATILE
    

    Option B:

    As Thilo suggested write two triggers that share the same trigger function.

    Triggers:

    CREATE TRIGGER mytrigger1
        BEFORE INSERT ON "mytable"
        FOR EACH ROW 
        WHEN NEW.score > 0
        EXECUTE PROCEDURE mytrigger();
    
    
    CREATE TRIGGER mytrigger2
        BEFORE UPDATE ON "mytable"
        FOR EACH ROW 
        WHEN (NEW.score > 0 AND OLD.score <> NEW.score)
        EXECUTE PROCEDURE mytrigger();
    

    Trigger function:

    CREATE OR REPLACE FUNCTION mytrigger()
      RETURNS trigger AS
    $BODY$
    begin
          YOUR CODE
    return new;
    end;
    $BODY$
      LANGUAGE plpgsql VOLATILE
    

提交回复
热议问题