Thursday, April 22, 2010

Declarations in Oracle PL/SQL

Your program stores values in variables and constants. As the program executes, the values of variables can change, but the values of constants cannot.

You can declare variables and constants in the declarative part of any PL/SQL block, subprogram, or package. Declarations allocate storage space for a value, specify its datatype, and name the storage location so that you can reference it.

A couple of examples follow:

crea_date DATE;

word_count SMALLINT := 0;



The first declaration names a variable of type DATE. The second declaration names a variable of type SMALLINT and uses the assignment operator to assign an initial value of zero to the variable.

The next examples show that the expression following the assignment operator can be arbitrarily complex and can refer to previously initialized variables:

pi REAL := 3.14159;

radius REAL := 1;

area REAL := pi * radius**2;

By default, variables are initialized to NULL. So, these declarations are equivalent:

birthday DATE;

birthday DATE := NULL;

In the declaration of a constant, the keyword CONSTANT must precede the type specifier, as the following example shows:

credit_limit CONSTANT REAL := 5000.00;

This declaration names a constant of type REAL and assigns an initial (also final) value of 5000 to the constant. A constant must be initialized in its declaration. Otherwise, you get a compilation error when the declaration is elaborated.

Restrictions on Declarations


PL/SQL does not allow forward references. You must declare a variable or constant before referencing it in other statements, including other declarative statements. For example, the following declaration of maxi is not allowed:

maxi INTEGER := 2 * mini; -- not allowed

mini INTEGER := 15;



However, PL/SQL does allow the forward declaration of subprograms. For more information, see "Declaring PL/SQL Subprograms".

Some languages allow you to declare a list of variables that have the same datatype. PL/SQL does not allow this. For example, the following declaration is not allowed:

i, j, k SMALLINT; -- not allowed



You must declare each variable separately:

i SMALLINT;

j SMALLINT;

k SMALLINT;


Using default           Using aliases