SQL-如果满足条件,则防止触发触发器

时间:2018-10-16 22:27:50

标签: sql oracle triggers

我有以下触发器

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;
/

基本上,当将新记录添加到EMP表时,将触发此触发器,它将新记录的原始EMP.DESCRIPTION设置为还包含名称和年龄信息'MR. {NAME}, Age {AGE}. {DESC}'。现在,我要检查NAME或AGE是否为NULL。如果是其中之一,那么我将阻止触发器格式化DESC列。这就是我一直在尝试的

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;
/

但是当我测试触发器时

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

,它只是向我显示错误:

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'

有什么办法可以实现这一目标?我曾考虑过使用IF语句,但找不到任何有用的东西。

1 个答案:

答案 0 :(得分:1)

只需使用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;
/