PLSQL :NEW and :OLD

前端 未结 13 1051
孤街浪徒
孤街浪徒 2020-12-24 06:30

Can anyone help me understand when to use :NEW and :OLD in PLSQL blocks, I\'m finding it very difficult to understand their usage.

相关标签:
13条回答
  • 2020-12-24 06:53

    :old and :new are pseudorecords referred to access row level data when using row level trigger.

    • :old - refers to Old Value
    • :new - refers to New value

    For Below operation, respective old and new values:

    1. INSERT- :old.value= NULL, :new value= post insert value
    2. DELETE- :old.value= Pre Delete value, :new value= null
    3. UPDATE- :old.value= Pre update value, :new value= Post Update value

    Eg:

    CREATE OR REPLACE TRIGGER get_dept
      BEFORE DELETE OR INSERT OR UPDATE ON employees
      FOR EACH ROW
    BEGIN
        DBMS_OUTPUT.PUT('Old Dept= ' || :OLD.dept|| ', ');
      DBMS_OUTPUT.PUT('New Dept= ' || :NEW.dept );
    END;
    

    Triggering Statement:

    UPDATE employees
    SET dept ='Accounts'
    WHERE empno IN (101 ,105);
    
    0 讨论(0)
  • 2020-12-24 06:54

    New and Old more relevant for update operation inside a trigger, to fetch old value of field use old and for recent value use new

    0 讨论(0)
  • 2020-12-24 07:01

    You normally use the terms in a trigger using :old to reference the old value and :new to reference the new value.

    Here is an example from the Oracle documentation linked to above

    CREATE OR REPLACE TRIGGER Print_salary_changes
      BEFORE DELETE OR INSERT OR UPDATE ON Emp_tab
      FOR EACH ROW
    WHEN (new.Empno > 0)
    DECLARE
        sal_diff number;
    BEGIN
        sal_diff  := :new.sal  - :old.sal;
        dbms_output.put('Old salary: ' || :old.sal);
        dbms_output.put('  New salary: ' || :new.sal);
        dbms_output.put_line('  Difference ' || sal_diff);
    END;
    

    In this example the trigger fires BEFORE DELETE OR INSERT OR UPDATE :old.sal will contain the salary prior to the trigger firing and :new.sal will contain the new value.

    0 讨论(0)
  • 2020-12-24 07:01

    You can use :OLD while working on after/before update 100% of time :NEW is a record of the new value added by (insert or update) :OLD is for old values. Without them, triggers are useless

    0 讨论(0)
  • 2020-12-24 07:02

    :new is the new value - After the trigger is fired this is the value of the column :old is the old value - After the trigger is fired this value is replaced with :new value

    0 讨论(0)
  • 2020-12-24 07:03

    :new means the new value your are trying to insert :old means the existing value in database

    0 讨论(0)
提交回复
热议问题