如何定义仅在特定列更新为特定值时触发的触发器?

时间:2014-09-17 08:19:01

标签: oracle triggers

请假设您有一个名为GOOFY的Oracle表。此表有一个名为MINNIE的列 我想编写一个仅在MINNIE列更新为'RUNNING'值时触发的触发器。 所以,我必须写下如下内容:

CREATE OR REPLACE TRIGGER MY_FIRST_SERIOUS_TRIGGER
BEFORE UPDATE
ON GOOFY
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
WHEN (UPPER(TRIM(:NEW.MINNIE)) = 'RUNNING')

...但我收到以下Oracle错误:

ORA-25000: invalid use of bind variable in trigger WHEN clause

通过更改触发器的标题,如下所示:

CREATE OR REPLACE TRIGGER MY_FIRST_SERIOUS_TRIGGER
BEFORE UPDATE
ON GOOFY
REFERENCING NEW AS NEW OLD AS OLD
WHEN (UPPER(TRIM(:NEW.MINNIE)) = 'RUNNING')

...我收到以下Oracle错误:

ORA-04077: WHEN clause cannot be used with table level triggers

我的触发器出了什么问题?

非常感谢您考虑过我的请求。

1 个答案:

答案 0 :(得分:2)

SQL> DROP TABLE t;
SQL>
SQL> CREATE TABLE t
  2    (
  3       x NUMBER,
  4       y NUMBER,
  5       z NUMBER
  6    );
SQL>
SQL> CREATE OR replace TRIGGER t_trigger
  2    AFTER UPDATE OR DELETE ON t
  3    FOR EACH ROW
  4    WHEN ( ( NEW.x <> OLD.x
  5              OR ( NEW.x IS NULL
  6                   AND OLD.x IS NOT NULL )
  7              OR ( NEW.x IS NOT NULL
  8                   AND OLD.x IS NULL ) )
  9            OR ( NEW.y <> OLD.y
 10                  OR ( NEW.y IS NULL
 11                       AND OLD.y IS NOT NULL )
 12                  OR ( NEW.y IS NOT NULL
 13                       AND OLD.y IS NULL ) ) )
 14  BEGIN
 15      dbms_output.Put_line('Trigger is fired');
 16  END;
 17
 18  /
SQL>
SQL> INSERT INTO t
  2  VALUES      ( 0,
  3               0,
  4               0 );
SQL>
SQL> SET feedback OFF;
SQL> UPDATE t
  2  SET    x = 0;
SQL>
SQL> UPDATE t
  2  SET    x = 1;
Trigger is fired
SQL>
SQL> UPDATE t
  2  SET    x = NULL;
Trigger is fired
SQL>
SQL> UPDATE t
  2  SET    x = 1;
Trigger is fired
SQL>
SQL> UPDATE t
  2  SET    x = 1;
SQL>

因此,只需使用

即可