[英]Update Column in a table using triggers while inserting value in another table
所以基本上我有這3個表及其列,
tbl_equipment
---->( equip_id
, equip_price
)
tbl_equiporder
---->( equip_id
, proj_no
, qty
)
tbl_project
----->( proj_no
, proj_balance
)
我需要編寫一個觸發器, proj_balance
在tbl_equiporder
表中插入值時更新tbl_equiporder
。
需要使用的公式是
balance = balance -(price*qty)
我需要從tbl_equiporder
獲取數量值,同時為同一張表編寫插入語句,以便可以使用它來更新tbl_project
的余額
我已經編寫了以下觸發器來更新在tbl_equiporder
表中插入時的tbl_equiporder
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.
您是否已閱讀有關此錯誤的信息? 您無法從要在觸發器中更改的表中進行選擇。
刪除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
在本地對tbl_equipment
的物化視圖一樣簡單。
您還正在通過數據庫鏈接選擇不必要的數據,不是。 我已經刪除了
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.