首页 > 解决方案 > 当插入/更新发生在同一个表中时触发更新特定列

问题描述

我试图编写一个触发器,当用户在同一个表中插入或更新一行时,它将更新一列。示例:插入用户(ID,F_NM,L_NM,EMAIL)值('1','John','Doe','john.doe@market.org.com');插入后,我想调用:更新用户集 ORG = 'market' 其中 ID = '1'。

create or replace trigger user_change
after insert or update of EMAIL on USER
for each row
declare
  NEW_ORG VARCHAR(10);
BEGIN
  CASE
    when :NEW.EMAIL like '$@market.org.com' then
      NEW_ORG := 'market';
    ........
  END CASE;

  UPDATE USER set ORG = NEW_ORG where ID = :NEW.ID
END;

计算新的 ORG 工作,但我无法让更新语句工作。我得到'ORA-04091 table USER is mutating,trigger/function may not see it',这是由于我同时插入/更新同一条记录。尝试将“pragma automatic_transaction”和“commit”添加到触发器中,字段的插入/更新有效,但 ORG 未更新。

还尝试更改为 INSTEAD OF INSERT OR UPDATE OF EMAIL 但我不断收到“ORA-04073 column list not valid for this trigger type”

create or replace trigger user_change
instead of insert or update of EMAIL on USER

虽然我得到'ORA-25002 不能在表上创建而不是触发器'

create or replace trigger user_change
instead of insert on USER

标签: sqloracletriggerssql-updatesql-insert

解决方案


当您可以在写入之前设置值时,为什么不简单地将触发器转换为前触发器呢?这样,您无需在表上运行新的 DML 语句,从而避免了“变异”错误。

create or replace trigger user_change
after insert or update of email on user
for each row
begin
    if :new.email like '%@market.org.com' then
        :new.org := 'market';
    end if;
end;

推荐阅读