【问题标题】:Update trigger on the same table on which update query is fired触发更新查询的同一表上的更新触发器
【发布时间】:2017-02-16 08:07:38
【问题描述】:

我的桌子

产品(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.

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

【问题讨论】:

    标签: sql oracle11g triggers oracle-sqldeveloper


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      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> 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-31
        • 1970-01-01
        • 2012-12-20
        • 1970-01-01
        • 2012-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多