new and old trigger code

后端 未结 4 1061
长情又很酷
长情又很酷 2020-12-30 14:53

can someone please explain what is meant by:

:new and :old in trigger code.

4条回答
  •  误落风尘
    2020-12-30 15:29

    :new and :old are pseudo-records that let you access the new and old values of particular columns. If I have a table

    CREATE TABLE foo (
      foo_id NUMBER PRIMARY KEY,
      bar    VARCHAR2(10),
      baz    VARCHAR2(10)
    );
    

    and I insert a row

    INSERT INTO foo( foo_id, bar, baz ) 
      VALUES( 1, 'Bar 1', 'Baz 1' );
    

    then in a row-level before insert trigger

    :new.foo_id will be 1
    :new.bar will be 'Bar 1'
    :new.baz will be 'Baz 1'
    

    while

    :old.foo_id will be NULL
    :old.bar will be NULL
    :old.baz will be NULL
    

    If you then update that row

    UPDATE foo
       SET baz = 'Baz 2'
     WHERE foo_id = 1
    

    then in a before update row-level trigger

    :new.foo_id will be 1
    :new.bar will be 'Bar 1'
    :new.baz will be 'Baz 2'
    

    while

    :old.foo_id will be 1
    :old.bar will be 'Bar 1'
    :old.baz will be 'Baz 1'
    

    If I then delete the row

    DELETE FROM foo
     WHERE foo_id = 1
    

    then in a before delete row-level trigger,

    :new.foo_id will be NULL
    :new.bar will be NULL
    :new.baz will be NULL
    

    while

    :old.foo_id will be 1
    :old.bar will be 'Bar 1'
    :old.baz will be 'Baz 2'
    

提交回复
热议问题