当 insert/update 发生在同一 table 时触发更新特定列

trigger to update specific column when insert/update happened in same table

我试图编写一个触发器,当用户在同一个 table 中插入或更新一行时,该触发器将更新列。 例子: 插入用户(ID,F_NM,L_NM,EMAIL)值('1','John','Doe','john.doe@market.org.com'); 插入后,我想调用:update user set ORG = 'market' where 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/funtion may not see it',我想这是由于我 inserting/updating 同时记录的。尝试将 'pragma autonomous_transaction' 和 'commit' 添加到触发器,字段的 insert/update 有效但 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 cannot create instead of triggers on tables'

create or replace trigger user_change
instead of insert on USER

为什么不简单地将触发器转换为 before 触发器,当您可以在写入值之前设置值?这样,您就不需要在 table 上 运行 新的 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;

看起来你的org列可以计算虚拟列。在这种情况下,最好创建 user-defined 确定性 pl/sql 函数 returns 正确计算值并将其添加到您的 table,例如:

Alter table t add org varchar2(30) generated always as (f_get_org(email))