在触发更新查询的同一 table 上更新触发器

Update trigger on the same table on which update query is fired

我的table

产品(P_name,new_price,old_price);

我想创建一个触发器,如果​​ new_price 被更新,那么 old_price 应该用之前的 new_price 更新。

SET SERVEROUTPUT ON;
CREATE OR REPLACE TRIGGER update_old_price
AFTER UPDATE ON product
FOR EACH ROW
BEGIN
  UPDATE product SET old_price = :old.new_price
  WHERE product_name=:old.product_name;
END;

但是显示错误

Error report -
SQL Error: ORA-04091: table MANIKIRAN.KODAM.PRODUCT is mutating, trigger/function may not see it
ORA-06512: at "MANIKIRAN.KODAM.UPDATE_OLD_PRICE", line 5
ORA-04088: error during execution of trigger 'MANIKIRAN.KODAM.UPDATE_OLD_PRICE'
04091. 00000 -  "table %s.%s is mutating, trigger/function may not see it"
*Cause:    A trigger (or a user defined plsql function that is referenced in
           this statement) attempted to look at (or modify) a table that was
           in the middle of being modified by the statement which fired it.
*Action:   Rewrite the trigger (or function) so it does not read that table.

所以请给我一个解决方案。

假设product_nameproducttable中是唯一的,只需使用一个before insert触发器:

CREATE OR REPLACE TRIGGER update_old_price
BEFORE UPDATE ON product
FOR EACH ROW
BEGIN
    SELECT :old.new_price INTO :new.old_price
    FROM dual;
END;

您可以通过以下方式进行。

CREATE TABLE product
(
   P_name      varchar2(30),
   new_price   NUMBER,
   old_price   NUMBER
)

触发器

CREATE OR REPLACE TRIGGER upd_prodt
   BEFORE UPDATE OF new_price
   ON product
   FOR EACH ROW
BEGIN
   :new.old_price := :old.new_price;
END;

演示:

SQL> select * from product;

 NEW_PRICE  OLD_PRICE
---------- ----------
        34         25

SQL> update product set new_price = 30 where new_price = 34;

1 row updated.

SQL> commit;

Commit complete.

SQL> select * from product;

 NEW_PRICE  OLD_PRICE
---------- ----------
        30         34

SQL>