繁体   English   中英

PL / SQL触发器在更新或插入后更新同一表

[英]PL/SQL trigger to update same table after update or insert

我需要触发器或类似内容的帮助。 问题是,我有几行具有相同的ID,并且有一列名为status的列。 这些行中只有一个可以同时处于“活动”状态。 在将一行更新为“活动”后,如何将所有其他更改为“非活动”。

如注释中所建议,您应该在存储过程中执行此操作,该存储过程可能类似于以下内容:

create or replace procedure prc_ActivateThingy(p_Id number) as
begin
  update YourThingy t
  set t.Active = 'Y'
  where
    t.Id = p_Id;

  dbms_output.put_line(sql%rowcount);

  if sql%rowcount = 0 then
    raise_application_error(-20000, 'No thingy found with id ' || p_Id || '.');
  end if;

  update YourThingy t
  set t.Active = 'N'
  where t.Id <> p_Id;

  dbms_output.put_line(sql%rowcount);
end;

在触发器中执行此操作也将起作用,但是如果“触发魔术”过多,最终您的应用程序将变得难以维护。 很难预测何时会触发什么,并且您会陷入混乱,使实施新的业务逻辑或技术重构变得困难。

因此,为了完整起见,这是在复合触发器中执行的方法,尽管同样,建议您选择上面的选项。

create or replace trigger tiuc_YourThingy
for insert or update on YourThingy
compound trigger

  v_Id number;

  before each row is
  begin
    v_Id := null;
    if :new.Active = 'Y' then
      v_Id := :new.Id;
    end if;
  end before each row;

  after statement is
  begin
    if v_Id is not null then
      update YourThingy t
      set
        t.ACTIVE = 'N'
      where
        t.ID <> v_Id;
    end if;
  end after statement;

end;

暂无
暂无

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

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