【问题标题】:Trigger - Can you conditionally execute depending on columns set in the transaction?触发器 - 您可以根据事务中设置的列有条件地执行吗?
【发布时间】:2013-03-23 01:58:12
【问题描述】:

如果更新语句中未指定列,是否仅设置值的控制触发器?例如,如果我在表/列上执行以下更新语句 -

update sampleTable set firstname='test', lastname='me' where id='id1';

在上述情况下,由于 firstname 和 lastname 列都已更新,我不希望在更新触发器之前执行任何操作。但是,如果执行以下语句 -

update sampleTable set firstname='test' where id='id1';

在上述情况下,由于 lastname 列没有更新,我想触发将 lastname 设置为 null。

我试过关注 -

Create or Replace Trigger testTrigger before update of firstname on sampleTable for each row
begin
   if :old.firstname != :new.firstname and :old.lastname = :new.lastname then
      :new.lastname = null;
   end if;
end;

这背后的想法是,如果我要执行上面的第一个更新语句,并且新的姓氏与以前的姓氏值不同,那么 :old 和 :new 将具有不同的值,因此 if 条件获胜'不满足,姓氏不会被设置为空。当然我错了,在两个更新语句中它仍然最终将 lastname 更新为 null。

我在这里有什么选择?我正在使用 Oracle 11g。

【问题讨论】:

    标签: oracle triggers oracle11g


    【解决方案1】:

    如果您希望在更新语句未引用此列的情况下将lastname 设置为空,那么您可以使用UPDATING() 函数。

    Create or Replace Trigger testTrigger 
    before update of firstname on sampleTable 
    for each row
    begin
       if not updating('LASTNAME') then
          :new.lastname := null;
       end if;
    end;
    /
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-03
      • 2023-02-14
      相关资源
      最近更新 更多