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

时间:2016-10-07 10:39:49

标签: sql oracle11g triggers oracle-sqldeveloper

我的表

产品(P_name,NEW_PRICE,OLD_PRICE);

我想创建一个触发器,以便在更新new_price时,应使用之前的new_price更新old_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.

所以请找一个解决方案。

2 个答案:

答案 0 :(得分:0)

假设product_name表中的product是唯一的,只需使用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;

答案 1 :(得分:0)

您可以采取以下方式。

breaking

触发

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;