Developing a Simple PL/SQL
Block
21
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder21Ć2
Developing a Simple PL/SQL Block 21Ć3
Objectives
In this lesson, you create a simple PL/SQL block after learning the various
elements that compose a block.
At the end of this lesson, you should be able to
D
Declare and use variables and constants in PL/SQL.
D
Assign new values to variables within the executable section.
D
Create and execute a named PL/SQL subprogram in Procedure Builder.
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder21Ć4
Developing a Simple PL/SQL Block 21Ć5
Overview
A PL/SQL block is comprised of up to three sections: declarative (optional),
executable (required), and exception handling (optional). Only BEGIN and END
keywords are required. Each subprogram contains an additional section, the header
(required).
You can store and change values within a PL/SQL block by declaring and referencing
variables and other identifiers.
Handling Variables
D
Declare and initialize variables within the declaration section.
D
Assign new values to variables within the executable section.
D
Pass values into PL/SQL blocks through parameters.
D
View the results from a PL/SQL block through output variables.
Note: The END keyword can be optionally followed by the name of the subprogram
for clarity.
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder21Ć6
Developing a Simple PL/SQL Block 21Ć7
Declaring PL/SQL Variables and Constants
You need to declare all identifiers within the declaration section before referencing
them within the PL/SQL block.
Syntax
identifier [CONSTANT] datatype [NOT NULL]
[:= | DEFAULT expr];
where: identifier is the name of the identifier.
CONSTANT constrains the identifier so that its value cannot
change; constants must be initialized.
datatype is a scalar or composite datatype.
NOT NULL constrains the variable so that it must contain a
value; NOT NULL variables must be initialized.
expr is any PL/SQL expression that can be a literal,
another variable, or an expression involving
operators and functions.
Guidelines
D
Name the identifier according to the same rules used for SQL objects.
D
You can use naming conventions, for example v_name to represent a variable, and
c_name to represent a constant.
D
You have the option of assigning an initial value to variables, unless they are
NOT NULL.
D
Initialize the variable to an expression with the assignment operator (:=), or,
equivalently, with the DEFAULT reserved word; otherwise, variables are
initialized to NULL by default.
D
Declare at most one identifier per line.
For more information, see
PL/SQL User’s Guide and Reference, Release 2.3, “Datatypes.”
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder21Ć8
Developing a Simple PL/SQL Block 21Ć9
Declaring Scalar Variables
PL/SQL supports three datatypes—scalar, composite, and reference—that you can
use for declaring variables, constants, and pointers.
Scalar Datatypes
A scalar datatype holds a single value and has no internal components. Scalar
datatypes can be classified into four categories: number, character, date and time, or
Boolean. Character and number datatypes have subtypes that associate a base type to
a constraint. For example, INTEGER and POSITIVE are subtypes of the NUMBER
base type.
Datatype
Description
BINARY_INTEGER Base type for integers between –2147483647
and 2147483647.
NUMBER [(precision,scale)] Base type for fixed and floating point numbers.
CHAR [(maximum_length)] Base type for fixed length character data up to
32767 bytes. If you do not specify a
maximum_length, the default length is set to 1.
LONG Base type for variable length character data up
to 32760 bytes.
LONG RAW Base type for binary data up to 32760 bytes.
VARCHAR2(maximum_length) Base type for variable length character data up
to 32767 bytes.
DATE Base type for dates and times.
BOOLEAN Base type that stores one of three possible
values used for logical calculations: TRUE,
FALSE, or NULL.
Note: The above list is abridged. For the complete list, see the PL/SQL User’s Guide
and Reference, Release 2.3, “Datatypes.”
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder21Ć10
Developing a Simple PL/SQL Block 21Ć11
Declaring Scalar Variables
continued
Examples
Declare a variable to store the gender code (M or F).
v_gender CHAR(1);
Declare a variable to count the iterations of a loop and initialize the variable to 0.
v_count BINARY_INTEGER := 0;
Declare a variable to accumulate the total salary for a department and initialize the
variable to 0.
v_total_sal NUMBER(9,2) := 0;
Declare a variable to store the ship date of an order, and initialize the variable to one
week from today.
v_order_date DATE := SYSDATE + 7;
Declare a constant for the tax rate, which never changes throughout the PL/SQL
block.
c_tax_rate CONSTANT NUMBER(3,2) := 8.25;
Declare a flag to indicate whether a piece of data is valid or invalid, and initialize the
variable to TRUE.
v_valid BOOLEAN NOT NULL := TRUE;
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder21Ć12
Developing a Simple PL/SQL Block 21Ć13
Declaring Scalar Variables
continued
The %TYPE Attribute
When you declare PL/SQL variables to hold column values, you must ensure that the
variable is of the correct datatype and precision. If it is not, then a PL/SQL error will
occur during execution.
Rather than hard-coding the datatype and precision of a variable, you can declare a
variable according to another previously-declared variable or database column. You
do this using the %TYPE attribute. To use the attribute in place of the datatype
required in the variable declaration, prefix it with the database table and column
names. If referring to a previously-declared variable, prefix the variable name to the
attribute.
PL/SQL determines the datatype and size of the variable when the block is compiled,
so the variable is always compatible with the database column or identifier used to
populate the variable.
Advantages of Using the %TYPE Attribute
D
The datatype of the underlying database column may be unknown.
D
The datatype of the underlying database column may change at runtime.
Examples
Declare variables to store the first and last names for an employee.
...
v_last_name s_emp.last_name%TYPE;
v_first_name s_emp.first_name%TYPE;
...
Declare variables to store the balance for a checking account, as well as the minimum
balance, which starts out as 10.
...
v_balance NUMBER(7,2);
v_minimum_balance v_balance%TYPE := 10;
...
A NOT NULL column constraint does not apply to variables declared using %TYPE.
Therefore, if you declare a variable using the %TYPE attribute using a database
column defined as NOT NULL, you can assign the NULL value to the variable.
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder21Ć14
Developing a Simple PL/SQL Block 21Ć15
Declaring Composite Datatypes
A composite datatype contains internal components and is reusable. Two types of
composite datatypes are available in PL/SQL: TABLE and RECORD.
PL/SQL Table
D
A PL/SQL TABLE datatype is not the same as a database table.
D
A PL/SQL TABLE is similar to a one-dimensional array.
D
A PL/SQL TABLE must contain two components:
D
A primary key of datatype BINARY_INTEGER that indexes the PL/SQL
TABLE.
D
A column of a scalar datatype, which stores the PL/SQL TABLE elements.
D
A PL/SQL TABLE can increase dynamically because it is unconstrained.
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder21Ć16
Developing a Simple PL/SQL Block 21Ć17
Declaring Composite Datatypes
continued
Declaring PL/SQL Tables
1.
Declare a TABLE datatype.
2.
Declare a variable of that datatype.
Syntax
TYPE type_name IS TABLE OF scalar_datatype [NOT NULL]
INDEX BY BINARY_INTEGER;
identifier type_name;
where: type_name is the name of the TABLE type.
scalar_datatype is the datatype of the PL/SQL TABLE elements.
You can use the %TYPE attribute.
identifier is the name of the identifier.
Example
Declare PL/SQL TABLE variables to store the first name and last name.
...
TYPE name_table_type IS TABLE OF VARCHAR2(25)
INDEX BY BINARY_INTEGER;
first_name_table name_table_type;
last_name_table name_table_type;
...
The NOT NULL constraint prevents nulls from being assigned to the PL/SQL
TABLE of that type. Do not initialize the PL/SQL TABLE.
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder21Ć18
Developing a Simple PL/SQL Block 21Ć19
Declaring Composite Datatypes
continued
PL/SQL RECORD
D
A PL/SQL RECORD datatype is not the same as a row in a database table.
D
A PL/SQL RECORD is similar in structure to a record in a 3GL.
D
A PL/SQL RECORD must contain one or more components of any scalar,
RECORD, or PL/SQL TABLE datatype called fields. These uniquely named
fields can have different datatypes.
D
The PL/SQL RECORD allows you to treat this collection of fields as one logical
unit.
D
PL/SQL RECORDS are convenient for fetching a row of data from a table for
processing in a PL/SQL block.
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder21Ć20
Developing a Simple PL/SQL Block 21Ć21
Declaring Composite Datatypes
continued
Declaring PL/SQL Records
1.
Declare a RECORD datatype.
2.
Declare a variable of that datatype.
Syntax
TYPE type_name IS RECORD
(field_name1 field_type
[NOT NULL {:=|DEFAULT} expr],
(field_name2 field_type
[NOT NULL {:=|DEFAULT} expr], ...);
identifier type_name;
where: type_name is the name of the RECORD type.
field_name is the name of the field.
field_type is the datatype of the field. You can use the
%TYPE and %ROWTYPE attribute.
expr is any PL/SQL expression that can be a literal,
another variable, or an expression involving
operators and functions.
identifier is the name of the identifier.
Example
Declare variables to store first name, last name, and gender of a new employee.
...
TYPE emp_record_type IS RECORD
(last_name VARCHAR2(25),
first_name VARCHAR2(25),
gender CHAR(1));
employee_record emp_record_type;
...
The NOT NULL constraint prevents the assigning of nulls to those fields. Be sure to
initialize NOT NULL fields.
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder21Ć22
Developing a Simple PL/SQL Block 21Ć23
Declaring Composite Datatypes
continued
Declaring Records with the %ROWTYPE Attribute
Declare a record based upon a collection of columns in a database table or view by
using the %ROWTYPE attribute. The fields within the record take their names and
datatypes from the columns of the table or view.
Advantages of Using the %ROWTYPE Attribute
D
The number and datatypes of the underlying database columns may be unknown.
D
The number and datatypes of the underlying database columns may change at
runtime.
D
Useful when retrieving a row with the SELECT statement.
Example
Declare a variable to store the same information about a department as it is stored in
the S_DEPT table.
...
dept_record s_dept%ROWTYPE;
...
This declaration creates a record with the same field names and field datatypes as a
row in a table. DEPT_RECORD is a record. The fields are: DEPT_RECORD.ID,
DEPT_RECORD.NAME, and DEPT_RECORD.REGION_ID.
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder21Ć24
Developing a Simple PL/SQL Block 21Ć25
PL/SQL Block Syntax Rules
Because PL/SQL is an extension of SQL, the general syntax rules that apply to SQL
are also applicable to the PL/SQL language.
Guidelines
D
Identifiers can contain up to 30 characters, but they must start with an alphabetic
character.
D
Reserved words cannot be used as identifiers unless they are enclosed within
double quotation marks (for example, “SELECT”).
D
Do not choose the same name for the identifier as the name of columns in a table
used in the block. If PL/SQL identifiers are in the same SQL statements and have
the same name as a column, then Oracle assumes that it is the column that is
being referenced.
D
Statements can be split across lines, but keywords must not be split.
D
Lexical units (for example, identifiers or literals) can be separated by one or more
spaces or other delimiters that cannot be confused as being part of the lexical unit.
D
Character and date literals must be enclosed within single quotation marks.
D
Numeric literals can be represented by either a simple value (for example, –32.5)
or by scientific notation (for example, 2E5, meaning 2x10 to the power of 5 =
200000).
D
Multiple line comments can be enclosed by /* and */ symbols. A single line
comment begins with --, and the end-of-line marks the comment’s end.
For more information, see
PL/SQL User’s Guide and Reference, Release 2.3, “Appendix E” for a list of reserved
words.