是否可以在触发器主体中使用未更新的列?

Is possible use a not updated column in trigger body?

我正在编写 DML 触发器以在新 table 中插入更新行。仅当更新一个列时才会触发触发器,但是...是否可以在 UPDATE OF one_single_column 子句之外的其他列中使用触发器主体?

审核TABLE:

CREATE TABLE employees_salary_history(
  user_name             VARCHAR2(45) NOT NULL,
  time_stamp            date DEFAULT (sysdate),
  employee_id           NUMBER(6),
  old_salary            NUMBER(8, 2),
  new_salary            NUMBER(8, 2),
  percente_raise_salary NUMBER(8, 2));

DML 触发器:

CREATE OR REPLACE TRIGGER update_salary_trg
AFTER
UPDATE 
OF salary
ON employees23
FOR EACH ROW
DECLARE
  v_user VARCHAR2(25);
BEGIN
  SELECT user
  INTO   v_user
  FROM   dual;

  INSERT INTO employees_salary_history
  VALUES(
      v_user, 
      sysdate, 
      employee_id, -- I would like add employee_id about employee that was updated, 
      :OLD.salary,
      :NEW.salary, 
      TRUNC((:NEW.salary - :OLD.salary) / :OLD.salary * 100, 3)
  );
END update_salary_trg;

当我省略 "employee_id" 列时,触发器会正常工作,但我想添加 employee_id 作为更新薪水的参考。当我添加 employee_id 列时,我收到以下错误:

Errors: check compiler log
Errores para TRIGGER HR.UPDATE_SALARY_TRG:

LINE/COL ERROR
-------- ----------------------------------
8/3      PL/SQL: SQL Statement ignored
8/15     PL/SQL: ORA-00913: too many values

是的,可以在触发器中使用 employees23-table 的任何列。

如果列未更改,则 :old:new 伪记录的值相同。

因此在您的情况下,只需使用 :new.employee_id

接下来推荐大家RTFM:PL/SQL Triggers。它还详细解释了伪记录何时可用以及它们包含什么值。

这是因为触发器无法引用 employee_id 字段。在您的情况下, New 和 OLD 将相同。所以只需将 employee_id 替换为 :OLD.employee_id 或 :NEW。 employee_id如下图。希望对你有帮助。

CREATE OR REPLACE TRIGGER update_salary_trg
AFTER
UPDATE 
OF salary
ON employees23
FOR EACH ROW
DECLARE
  v_user VARCHAR2(25);
BEGIN
  SELECT user
  INTO   v_user
  FROM   dual;

  INSERT INTO employees_salary_history --employees_salary_history
  VALUES(
      v_user, 
      sysdate, 
      :NEW.employee_id, -- I would like add employee_id about employee that was updated, 
      :OLD.salary,
      :NEW.salary, 
      TRUNC((:NEW.salary - :OLD.salary) / :OLD.salary * 100, 3)
  );
END update_salary_trg;