Pages

OracleEBSpro is purely for knowledge sharing and learning purpose, with the main focus on Oracle E-Business Suite Product and other related Oracle Technologies.

I'm NOT responsible for any damages in whatever form caused by the usage of the content of this blog.

I share my Oracle knowledge through this blog. All my posts in this blog are based on my experience, reading oracle websites, books, forums and other blogs. I invite people to read and suggest ways to improve this blog.


Wednesday, February 20, 2013

Scalar and Composite Variables


Scalar Variable Declaration

A scalar variable stores a value with no internal components. The value can change.

A scalar variable declaration specifies the name and data type of the variable and allocates storage for it. The declaration can also assign an initial value and impose theNOT NULL constraint.

You reference a scalar variable by its name.

DECLARE
  part_number       NUMBER(6);     -- SQL data type
  part_name         VARCHAR2(20);  -- SQL data type
  in_stock          BOOLEAN;       -- PL/SQL-only data type
  part_price        NUMBER(6,2);   -- SQL data type
  part_description  VARCHAR2(50);  -- SQL data type
BEGIN
  NULL;
END;
/

Composite Variables

composite variable has internal components, which you can access individually. You can pass entire composite variables to subprograms as parameters. PL/SQL has two kinds of composite variables, collections and records.
In a collection, the internal components are always of the same data type, and are called elements. You access each element by its unique index. Lists and arrays are classic examples of collections.
Collection TypeNumber of ElementsIndex TypeDense or SparseUninitialized StatusWhere DefinedCan Be ADT Attribute Data Type
Associative array (or index-by table)
Unspecified
String orPLS_INTEGER
Either
Empty
In PL/SQL block or package
No
VARRAY (variable-size array)
Specified
Integer
Always dense
Null
In PL/SQL block or package or at schema level
Only if defined at schema level
Nested table
Unspecified
Integer
Starts dense, can become sparse
Null
In PL/SQL block or package or at schema level
Only if defined at schema level
In a record, the internal components can be of different data types, and are called fields. You access each field by its name. A record variable can hold a table row, or some columns from a table row.
An associative array (formerly called PL/SQL table or index-by table) is a set of key-value pairs. Each key is a unique index, used to locate the associated value with the syntax variable_name(index).
Example: Associative Array Indexed by String
DECLARE
  -- Associative array indexed by string:
  
  TYPE population IS TABLE OF NUMBER  -- Associative array type
    INDEX BY VARCHAR2(64);            --  indexed by string
  
  city_population  population;        -- Associative array variable
  i  VARCHAR2(64);                    -- Scalar variable
  
BEGIN
  -- Add elements (key-value pairs) to associative array:
 
  city_population('Smallville')  := 2000;
  city_population('Midland')     := 750000;
  city_population('Megalopolis') := 1000000;
 
  -- Change value associated with key 'Smallville':
 
  city_population('Smallville') := 2001;
 
  -- Print associative array:
 
  i := city_population.FIRST;  -- Get first element of array
 
  WHILE i IS NOT NULL LOOP
    DBMS_Output.PUT_LINE
      ('Population of ' || i || ' is ' || city_population(i));
    i := city_population.NEXT(i);  -- Get next element of array
  END LOOP;
END;
/

 varray (variable-size array) is an array whose number of elements can vary from zero (empty) to the declared maximum size. To access an element of a varray variable, use the syntax variable_name(index).

Example: Varray (Variable-Size Array)

DECLARE
  TYPE Foursome IS VARRAY(4) OF VARCHAR2(15);  -- VARRAY type
 
  -- varray variable initialized with constructor:
 
  team Foursome := Foursome('John', 'Mary', 'Alberto', 'Juanita');
 
  PROCEDURE print_team (heading VARCHAR2) IS
  BEGIN
    DBMS_OUTPUT.PUT_LINE(heading);
 
    FOR i IN 1..4 LOOP
      DBMS_OUTPUT.PUT_LINE(i || '.' || team(i));
    END LOOP;
 
    DBMS_OUTPUT.PUT_LINE('---'); 
  END;
  
BEGIN 
  print_team('2001 Team:');
 
  team(3) := 'Pierre';  -- Change values of two elements
  team(4) := 'Yvonne';
  print_team('2005 Team:');
 
  -- Invoke constructor to assign new values to varray variable:
 
  team := Foursome('Arun', 'Amitha', 'Allan', 'Mae');
  print_team('2009 Team:');
END;
/

In the database, a nested table is a column type that stores an unspecified number of rows in no particular order. When you retrieve a nested table value from the database into a PL/SQL nested table variable, PL/SQL gives the rows consecutive indexes, starting at 1. Using these indexes, you can access the individual rows of the nested table variable. The syntax is variable_name(index). The indexes and row order of a nested table might not remain stable as you store and retrieve the nested table from the database.


Example: Nested Table of Local Type
DECLARE
  TYPE Roster IS TABLE OF VARCHAR2(15);  -- nested table type
 
  -- nested table variable initialized with constructor:
 
  names Roster := Roster('D Caruso', 'J Hamil', 'D Piro', 'R Singh');
 
  PROCEDURE print_names (heading VARCHAR2) IS
  BEGIN
    DBMS_OUTPUT.PUT_LINE(heading);
 
    FOR i IN names.FIRST .. names.LAST LOOP  -- For first to last element
      DBMS_OUTPUT.PUT_LINE(names(i));
    END LOOP;
 
    DBMS_OUTPUT.PUT_LINE('---');
  END;
  
BEGIN 
  print_names('Initial Values:');
 
  names(3) := 'P Perez';  -- Change value of one element
  print_names('Current Values:');
 
  names := Roster('A Jansen', 'B Gupta');  -- Change entire table
  print_names('Current Values:');
END;
/
Result:
Initial Values:
D Caruso
J Hamil
D Piro
R Singh
---
Current Values:
D Caruso
J Hamil
P Perez
R Singh
---
Current Values:
A Jansen
B Gupta

Important Differences Between Nested Tables and Arrays

Conceptually, a nested table is like a one-dimensional array with an arbitrary number of elements. However, a nested table differs from an array in these important ways:
  • An array has a declared number of elements, but a nested table does not. The size of a nested table can increase dynamically.
  • An array is always dense. A nested array is dense initially, but it can become sparse, because you can delete elements from it.
Figure 5-2 shows the important differences between a nested table and an array.
Figure 5-2 Array and Nested Table
Description of Figure 5-2 follows
Collection Methods
MethodTypeDescription
DELETE
Procedure
Deletes elements from collection.
TRIM
Procedure
Deletes elements from end of varray or nested table.
EXTEND
Procedure
Adds elements to end of varray or nested table.
EXISTS
Function
Returns TRUE if and only if specified element of varray or nested table exists.
FIRST
Function
Returns first index in collection.
LAST
Function
Returns last index in collection.
COUNT
Function
Returns number of elements in collection.
LIMIT
Function
Returns maximum number of elements that collection can have.
PRIOR
Function
Returns index that precedes specified index.
NEXT
Function
Returns index that succeeds specified index.

Record Variables

You can create a record variable in any of these ways:
  • Define a RECORD type and then declare a variable of that type.
  • Use %TYPE to declare a record variable of the same type as a previously declared record variable.
  • Use %ROWTYPE to declare a record variable that represents either a full or partial row of a database table or view.
    Example: Declaring Record Constant
    CREATE OR REPLACE PACKAGE My_Types AUTHID DEFINER IS
      TYPE My_Rec IS RECORD (a NUMBER, b NUMBER);
      FUNCTION Init_My_Rec RETURN My_Rec;
    END My_Types;
    /
    CREATE OR REPLACE PACKAGE BODY My_Types IS
      FUNCTION Init_My_Rec RETURN My_Rec IS
        Rec My_Rec;
      BEGIN
        Rec.a := 0;
        Rec.b := 1;
        RETURN Rec;
      END Init_My_Rec;
    END My_Types;
    /
    DECLARE
      r CONSTANT My_Types.My_Rec := My_Types.Init_My_Rec();
    BEGIN
      DBMS_OUTPUT.PUT_LINE('r.a = ' || r.a);
      DBMS_OUTPUT.PUT_LINE('r.b = ' || r.b);
    END;
    /
    
    Result:
    r.a = 0
    r.b = 1
     
    PL/SQL procedure successfully completed.
    
    
    Example %ROWTYPE Variable Represents Full Database Table Row
    DECLARE
      dept_rec departments%ROWTYPE;
    BEGIN
      -- Assign values to fields:
      
      dept_rec.department_id   := 10;
      dept_rec.department_name := 'Administration';
      dept_rec.manager_id      := 200;
      dept_rec.location_id     := 1700;
     
      -- Print fields:
     
      DBMS_OUTPUT.PUT_LINE('dept_id:   ' || dept_rec.department_id);
      DBMS_OUTPUT.PUT_LINE('dept_name: ' || dept_rec.department_name);
      DBMS_OUTPUT.PUT_LINE('mgr_id:    ' || dept_rec.manager_id);
      DBMS_OUTPUT.PUT_LINE('loc_id:    ' || dept_rec.location_id);
    END;
    /
    
    Result:
    dept_id:   10
    dept_name: Administration
    mgr_id:    200
    loc_id:    1700
    
    
    http://docs.oracle.com/cd/E11882_01/appdev.112/e17126/composites.htm#CIHFCFCJ
    
    
    
    

4 comments: