簡體   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