在另一个表中插入值时,使用触发器更新表中的列

时间:2013-09-11 07:45:23

标签: sql oracle plsql triggers

所以基本上我有这三个表及其列,

tbl_equipment ----> (equip_idequip_price

tbl_equiporder ----> (equip_idproj_noqty

tbl_project -----> (proj_noproj_balance

我需要编写一个触发器,在proj_balance表中插入值时更新tbl_equiporder

需要使用的公式是

balance = balance -(price*qty)

我需要在为同一个提到的表编写insert语句时从tbl_equiporder获取qty值,以便我可以使用它来更新tbl_project中的余额

我编写了以下触发器来更新插入tbl_equiporder

时的proj_balance
CREATE OR REPLACE TRIGGER trigger_equiporder
AFTER INSERT OR UPDATE OR DELETE ON tbl_equiporder FOR EACH ROW    
  DECLARE
    t_equipid NUMBER(4);
    t_price   NUMBER(4);
    t_qty     NUMBER(4);
    t_balance NUMBER(4);
  BEGIN

    SELECT equip_id, equip_price INTO t_equipid, t_price
      FROM tbl_equipment@fit5043a
     WHERE equip_id = :new.equip_id;

    SELECT equip_qty INTO t_qty
      FROM tbl_equiporder
     WHERE equip_id = :new.equip_id;

    SELECT proj_balance INTO t_balance
      FROM tbl_project
     WHERE proj_no = :new.proj_no;

    t_balance := t_balance - (t_price * t_qty);

    UPDATE tbl_project
       SET proj_balance = t_balance
     WHERE proj_no = :new.proj_no;

  END;

当我写下插入语句

INSERT INTO tbl_equiporder VALUES (1, 101, 1);

它引发了以下错误

Error starting at line 1 in command:
INSERT INTO tbl_equiporder VALUES (1,101,'11-sep-13',1000,1)
Error report:
SQL Error: ORA-04091: table S24585181.TBL_EQUIPORDER is mutating, trigger/function may not see it
ORA-06512: at "S24585181.TRIGGER_EQUIPORDER", line 9
ORA-04088: error during execution of trigger 'S24585181.TRIGGER_EQUIPORDER'
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.

1 个答案:

答案 0 :(得分:1)

你有没有读过这个错误?您无法从您在触发器中更改的表中进行选择。

删除SELECT并仅使用已有的值。

create or replace trigger trigger_equiporder 
 after insert or update or delete on tbl_equiporder
 for each row  

declare
   t_price number(4);
   t_qty number(4);
   t_balance number(4);
begin

   select equip_price into t_price 
     from tbl_equipment@fit5043a 
    where equip_id = :new.equip_id;

   select proj_balance into t_balance 
     from tbl_project 
    where proj_no = :new.proj_no;

    t_balance := t_balance -(t_price * :new.equip_qty);

   update tbl_project 
      set proj_balance = t_balance 
    where proj_no = :new.proj_no;

end;

我对这一切都非常谨慎;您似乎在触发器中执行跨数据库SELECT,这将大大减慢它的速度。似乎值得查看您的数据模型以确定它是否可以改进;即使它只是在本地具有tbl_equipment的物化视图这么简单。

您还在数据库链接中选择不必要的数据,不这样做。我已将其删除