表正在突变,触发器/函数可能看不到错误oracle db

时间:2018-12-11 19:35:32

标签: oracle triggers

更新列时出现问题。我有一个包含两个表的数据库,这是这些表的create语句:

create table trein (
trein_id number primary key,
naam varchar2(100) not null unique,
zitplekken number);

create table wagon(
wagon_id number primary key,
naam varchar2(100) not null unique,
zitplekken number not null,
trein_naam_fk varchar2(100));

如果我向wagon.trein_naam_fk添加一个值,我想从同一行中获取zitplekken的值并将其添加到相关的train.zitplekken中。所以我为此编写了触发器:

CREATE OR REPLACE TRIGGER KOPPELWAGON_TRIGGER
AFTER UPDATE OF TREIN_NAAM_FK on WAGON
   FOR EACH ROW

DECLARE
   V_ZITPLEKKEN_W number;
   V_ZITPLEKKEN_T number;
   V_TREIN_NAAM varchar(100);
BEGIN

   -- Haal zitplaatsen wagon op
   SELECT ZITPLEKKEN, TREIN_NAAM_FK INTO V_ZITPLEKKEN_W, V_TREIN_NAAM FROM WAGON WHERE NAAM = :OLD.NAAM;
   -- Verhoog zitplekken trein
   UPDATE TREIN SET ZITPLEKKEN = ZITPLEKKEN + V_ZITPLEKKEN_W WHERE NAAM = V_TREIN_NAAM;
END;

/

当我运行以下更新语句时,出现错误:

UPDATE WAGON SET TREIN_NAAM_FK = 't1' WHERE NAAM = 'w1';


Error starting at line : 1 in command -
UPDATE WAGON SET TREIN_NAAM_FK = 't1' WHERE NAAM = 'w1'
Error report -
ORA-04091: table RICHRAIL.WAGON is mutating, trigger/function may not see it
ORA-06512: at "RICHRAIL.KOPPELWAGON_TRIGGER", line 8
ORA-04088: error during execution of trigger 'RICHRAIL.KOPPELWAGON_TRIGGER'

有什么主意我在这里做错什么吗?

1 个答案:

答案 0 :(得分:3)

您无法从创建触发器的触发器中的同一表中选择数据,由于此冲突,您遇到了问题。根据我的理解,甚至不需要从同一张表中选择数据,因此您的触发代码应如下所示:

CREATE OR REPLACE TRIGGER KOPPELWAGON_TRIGGER
AFTER UPDATE OF TREIN_NAAM_FK on WAGON
   FOR EACH ROW

/*DECLARE
   V_ZITPLEKKEN_W number;
   V_ZITPLEKKEN_T number;
   V_TREIN_NAAM varchar(100); */
BEGIN

   -- Haal zitplaatsen wagon op
--  SELECT ZITPLEKKEN, TREIN_NAAM_FK INTO V_ZITPLEKKEN_W, V_TREIN_NAAM FROM WAGON WHERE NAAM = :OLD.NAAM;
   -- Verhoog zitplekken trein
   UPDATE TREIN SET ZITPLEKKEN = ZITPLEKKEN + :OLD.ZITPLEKKEN WHERE NAAM = :OLD.TREIN_NAAM_FK;
END;