简体   繁体   中英

SQL - prevent trigger from firing if a condition is met

I'm having the following trigger

CREATE OR REPLACE TRIGGER MODIFY_EMP_DESC
BEFORE INSERT ON EMP
    FOR EACH ROW
BEGIN
    SELECT 'MR. ' :NEW.NAME || ', Age: ' || :NEW.AGE || '. '|| :NEW.DESC || INTO :NEW.DESC FROM DUAL;
END;
/

Basically, this trigger fires when a new record is added to the EMP table, it sets the original EMP.DESCRIPTION of that new record to also contain the name and age information 'MR. {NAME}, Age {AGE}. {DESC}' 'MR. {NAME}, Age {AGE}. {DESC}' 'MR. {NAME}, Age {AGE}. {DESC}' . Now I want to check if either NAME or AGE is NULL. If one of them is, then I prevent the trigger from formatting the DESC column. This is what I have been trying

CREATE OR REPLACE TRIGGER MODIFY_EMP_DESC
BEFORE INSERT ON EMP
    FOR EACH ROW
BEGIN
    SELECT 'MR. ' :NEW.NAME || ', Age: ' || :NEW.AGE || '. '|| :NEW.DESC || INTO :NEW.DESC FROM DUAL
    WHERE :NEW.NAME IS NOT NULL 
        AND :NEW.AGE IS NOT NULL
END;
/

But when I test my trigger

INSERT INTO EMP (ID, DESC) VALUES (123, 'ACCOUNTANT.');

, it just showed me the error:

ERROR at line 1:
ORA-01403: no data found
ORA-06512: at "MIKE.MODIFY_EMP_DESC", line 2
ORA-04088: error during execution of trigger 'MIKE.MODIFY_EMP_DESC'

Is there any way that I can achieve this? I've thought about using IF statements but I could not find anything useful.

Just use PL/SQL:

CREATE OR REPLACE TRIGGER MODIFY_EMP_DESC
BEFORE INSERT ON EMP
    FOR EACH ROW
BEGIN
    if :NEW.NAME IS NOT NULL
    AND :NEW.AGE IS NOT NULL
    then
        :NEW.DESC :=  'MR. '|| :NEW.NAME || ', Age: ' || :NEW.AGE || '. '|| :NEW.DESC;
    end if;  

END;
/

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