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



我需要触发器或类似东西的帮助。问题是,我有几行具有相同的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;

最新更新