繁体   English   中英

在同一个表中发生插入/更新时触发更新特定列

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

我试图编写一个触发器,当用户在同一个表中插入或更新一行时,它会更新一列。 示例:插入 user(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 表用户正在发生变异,触发器/功能可能看不到它”,这是由于我同时插入/更新相同的记录。 尝试将 'pragma Autonomous_transaction' 和 'commit' 添加到触发器中,字段的插入/更新有效,但 ORG 未更新。

还尝试更改为 INSTEAD OF INSERT OR UPDATE OF EMAIL 但我不断收到“ORA-04073 列列表对此触发器类型无效”

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

当您可以在写入之前设置值时,为什么不简单地将触发器转换为触发器? 这样,您就不需要在表上运行新的 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列可以计算为虚拟列。 在这种情况下,最好创建用户定义的确定性 pl/sql 函数,该函数返回正确的计算值并将其添加到您的表中,例如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM