PL/SQL 触发器在更新或插入后更新相同的 table

PL/SQL trigger to update same table after update or insert

我需要触发器或类似的帮助。问题是,我有几行具有相同的 id,并且有一个名为 status 的列。这些行中只有一行可以同时 'active'。如何在一行更新为 'active'.

后将所有其他更改为 'inactive'

正如评论中所建议的那样,您应该在存储过程中执行此操作,它可能看起来像这样:

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;

在触发器中执行此操作也可以,但如果太多 'trigger magic',最终您的应用程序将变得难以维护。预测何时触发变得更加困难,并且您可能会陷入混乱,从而难以实施新的业务逻辑或技术重构。

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

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;