Oracle 触发器:当以冒号 (:) 为前缀 NEW 时

Oracle Trigger: When Prefix NEW with Colon (:)

Here我找到了下面的例子

CREATE OR REPLACE TRIGGER Print_salary_changes
  BEFORE DELETE OR INSERT OR UPDATE ON Emp_tab
  FOR EACH ROW
WHEN (new.Empno > 0)
DECLARE
    sal_diff number;
BEGIN
    sal_diff  := :new.sal  - :old.sal;
    dbms_output.put('Old salary: ' || :old.sal);
    dbms_output.put('  New salary: ' || :new.sal);
    dbms_output.put_line('  Difference ' || sal_diff);
END;
/

WHEN 中我写 new 而在 BEGIN 之后我写 :newnew:new

有什么区别

From the documentation:

In the trigger_body of a simple trigger or the tps_body of a compound trigger, a correlation name is a placeholder for a bind variable. Reference the field of a pseudorecord with this syntax:

:pseudorecord_name.field_name

In the WHEN clause of a conditional trigger, a correlation name is not a placeholder for a bind variable. Therefore, omit the colon in the preceding syntax.

所以你在这一行中没有冒号:

WHEN (new.Empno > 0)

但是你在正文中做,例如:

sal_diff  := :new.sal  - :old.sal;

触发器有时会引起混淆,因为它们分为两部分;本质上是一个 SQL/DDL 部分,在您的情况下是:

CREATE OR REPLACE TRIGGER Print_salary_changes
  BEFORE DELETE OR INSERT OR UPDATE ON Emp_tab
  FOR EACH ROW
WHEN (new.Empno > 0)

然后是 PL/SQL 正文,在您的情况下,正文从以下位置开始:

DECLARE

但在其他情况下不会有声明部分,然后它会从

开始
BEGIN

当触发器出现编译错误时,为 PLS- 错误报告的行号从 PL/SQL 部分开始计算,而不是从 CREATE 开始 - 这可能会造成混淆...