Thursday 6 September 2007

PL/SQL Records

A PL/SQL record is a variable that contains a collection of separate fields. Each field is individually addressable. You can reference the field names in both assignments and expressions. The fields within a record may have different datatypes and sizes, like the columns of a database table. Records are a convenient way of storing a complete fetched row from a database table.

Use the %ROWTYPE attribute to declare a record based upon a collection of database columns from a table or view. The fields within the record take their names and datatypes from the columns of the table or view.

Declare the record in the DECLARE section along with any other required variables and constants. An example follows :
DECLARE
REC1 JD11.BOOK%ROWTYPE;
REC4 JD11.BOOK%ROWTYPE;

The above declaration sets the object REC1 to be a record object holding fields that match the columns in the BOOK table. It doesn't hold any values until it is populated.

Assign values into a PL/SQL record by naming the record after the INTO keyword of a SELECT statement. The INTO keyword defines the name specification for the storage area(s) of queried value(s).
BEGIN
SELECT * FROM JD11.BOOK INTO REC1 WHERE ISBN = 21;
END;

You can assign all the record values from one record to another provided that the record definitions are the same.

BEGIN
REC4 := REC1;
END;

Reference the field values within a PL/SQL record like this :

BEGIN
REC4 := REC1;
IF REC4.COST > 0 THEN
REC4.SECTION_ID := 10;
ELSE
REC4.SECTION_ID := 7;
END IF;
END;