Home > front end >  Create trigger to update same table after insert
Create trigger to update same table after insert

Time:11-13

I need some help to automatically ignore some data (after insert) on the table in order for it not to process those records:

CREATE or REPLACE TRIGGER "user"."trigger_name"
AFTER INSERT ON user.tab
FOR EACH ROW
BEGIN
    UPDATE tab
       SET :NEW.status = 'DONE'
     WHERE :NEW.type not in (1, 2)
       AND :NEW.status = 'NEW'
    COMMIT;
END trigger_name;

Will this be a proper approach?

Thanks a lot!

CodePudding user response:

I think you're looking for something more like this, as suggested above:

CREATE or REPLACE TRIGGER user.trigger_name
BEFORE INSERT ON user.table
FOR EACH ROW
BEGIN
    if :new.status = 'NEW' and :new.type not in (1,2) then
        :new.status = 'DONE';
    end if;
END trigger_name;

CodePudding user response:

I recommend that you add a virtual column for the column status rather than creating a DB trigger. Since you may encounter the cases that the trigger is disabled unconsciously. This may yield some data to conform the rule while some of them don't. Moreover, this way, you will be able to keep track of the original data.

So, consider applying the following DDL statement

ALTER TABLE tab
ADD (
     status2 AS (CASE 
                 WHEN status = 'NEW' AND type NOT IN (1,2) THEN 
                      'DONE' 
                 ELSE 
                      status 
                  END)
);

Demo

  • Related