在oracle中使用:new和new in触发器有什么区别?

时间:2017-06-18 20:05:08

标签: sql oracle plsql triggers oracle-sqldeveloper

例如,

我有这个触发器

CREATE OR REPLACE TRIGGER SAL_REDUCE
BEFORE UPDATE ON DRIVER --or insert--
FOR EACH ROW
BEGIN
IF(NEW.SAL < 1000) THEN
RAISE_APPLICATION_ERROR(-20001,'SALARY CANNOT BE REDUCED!!! PAY THEM MORE');
END IF;
END;
/

和此触发器

CREATE OR REPLACE TRIGGER Salary_check
BEFORE INSERT OR UPDATE OF Sal, Job ON Emp99
FOR EACH ROW
DECLARE
Minsal NUMBER;
Maxsal NUMBER;
Salary_out_of_range   EXCEPTION;
BEGIN

/* Retrieve the minimum and maximum salary for the
employee's new job classification from the SALGRADE
table into MINSAL and MAXSAL: */

SELECT Minsal, Maxsal INTO Minsal, Maxsal FROM Salgrade
WHERE Job_classification = :new.Job;
IF (:new.Sal < Minsal OR :new.Sal > Maxsal) THEN
  RAISE Salary_out_of_range;
END IF;
EXCEPTION
WHEN Salary_out_of_range THEN
  Raise_application_error (-20300,
     'Salary '||TO_CHAR(:new.Sal)||' out of range for '
     ||'job classification '||:new.Job
     ||' for employee '||:new.Ename);
WHEN NO_DATA_FOUND THEN
  Raise_application_error(-20322,
     'Invalid Job Classification '
     ||:new.Job_classification);
END;
/

所以,在第二个例子中,你注意到了:正如我在标题中描述的那样使用new,而在第一个例子中,使用了new而没有冒号。这两者有什么区别?

谢谢!

1 个答案:

答案 0 :(得分:1)

第一个触发器在语法上是不正确的。正如Nicholas已经评论过的那样,触发器的主体内部需要:new

需要new.的唯一位置是触发器定义的WHEN子句。例如:

CREATE OR REPLACE TRIGGER SAL_REDUCE
BEFORE UPDATE ON DRIVER --or insert--
FOR EACH ROW
WHEN (NEW.SAL > 100)
BEGIN
  IF(:NEW.SAL < 1000) THEN
    RAISE_APPLICATION_ERROR(-20001,'SALARY CANNOT BE REDUCED!!! PAY THEM MORE');
  END IF;
END;
/

在这个愚蠢的设计示例中,触发器只会在SAL超过100时触发。