Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PLSQL :NEW and :OLD

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

like image 538
Pravin Avatar asked Oct 30 '12 08:10

Pravin


People also ask

What is new in Oracle PL SQL?

NEW and OLD are pseudorecords that the PL/SQL runtime engine creates and populates whenever a row-level trigger fires. OLD and NEW store the original and new values, respectively, of the record being processed by the trigger. They are called pseudorecords because they do not have all properties of PL/SQL records.

How do you use new and old in triggers?

You normally use the terms in a trigger using :old to reference the old value and :new to reference the new value. CREATE OR REPLACE TRIGGER Print_salary_changes BEFORE DELETE OR INSERT OR UPDATE ON Emp_tab FOR EACH ROW WHEN (new.

How many types of PL SQL are there?

Answer: The PL SQL data types are composite and scalar. The scalar data types can hold single values like Character, Number, Boolean, and DateTime. While the composite data types store more than one value like collection and record.


2 Answers

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.

like image 196
GrahamA Avatar answered Oct 03 '22 23:10

GrahamA


:New and :Old Value can be differentiated in DML Statements .
Insert -- :Old = NULL :New= Inserted new value

Update -- :Old = Value present in table before the Update statement Triggered :New = Given new value to Update

Delete -- :Old = Value before deletion :New = NULL

like image 30
Gok Avatar answered Oct 03 '22 21:10

Gok