代码之家  ›  专栏  ›  技术社区  ›  guigui42

如何防止在未插入行时触发插入触发器?

  •  3
  • guigui42  · 技术社区  · 15 年前

    我有一张桌子。在这个表上,我创建了一个触发器:在插入、更新或删除之后

    现在,如果我执行一个不插入任何内容的插入操作,触发器仍将被激发:

    insert into TABLE1 select * from TABLE1 where 1=0;
    

    此查询将不插入任何行,但触发器仍被激发。

    有没有办法避免这种情况?这是正常行为吗?

    3 回复  |  直到 8 年前
        1
  •  4
  •   Tony Andrews    15 年前

    是的,这是正常的行为。可以避免,但这样做需要有3个触发器:

    1. 用于将包布尔变量设置为false的before触发器
    2. 一个for each row触发器,用于在插入行时将变量设置为true。
    3. 您拥有的after触发器,现在您可以在执行其操作之前检查变量的值。

    听起来像是杀戮过度?也许是:用你的扳机能达到什么目的?

        2
  •  3
  •   Vincent Malgrat    15 年前

    This is the normal behaviour, Oracle is expecting to insert row so it fires both BEFORE INSERT and AFTER INSERT triggers, even if no row is inserted. One of the purpose of the AFTER triggers is to do some action after a statement succeeds. This statement succeeded :)

    您可以计算受包变量影响的行数:

    • 设置 mypackage.table1_nb_ins 插入前触发器中的变量为0
    • 为每行触发器增加一个after inesrt中的计数器

    如果计数器大于0,则执行插入后逻辑

        3
  •  0
  •   C.B.Luca    8 年前

    行触发器

    A row trigger is fired each time the table is affected by the triggering statement. For example, if an UPDATE statement updates multiple rows of a table, a row trigger is fired once for each row affected by the UPDATE statement. If a triggering statement affects no rows, a row trigger is not run.

    https://docs.oracle.com/cd/B19306_01/server.102/b14220/triggers.htm