简体   繁体   中英

Create trigger to update same table after insert

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!

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM