我需要触发器的帮助或类似的东西。问题是,我有几行具有相同的ID,并且有一列名为status的列。这些行中只有一个可以同时处于“活动”状态。在将一行更新为“活动”后如何将所有其他更改为“非活动”。
答案 0 :(得分:2)
如注释中所建议,您应该在存储过程中执行此操作,该过程可能类似于以下内容:
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;