You are on page 1of 108

Chapter 4:

Introduction to PL/SQL

Guide to Oracle 10g


Lesson A Objectives
After completing this lesson, you should be able to:
• Describe the fundamentals of the PL/SQL
programming language
• Write and execute PL/SQL programs in SQL*Plus
• Execute PL/SQL data type conversion functions
• Display output through PL/SQL programs
• Manipulate character strings in PL/SQL programs
• Debug PL/SQL programs

Guide to Oracle 10g 2


Introduction
• DB users use GUI applications to enter data into
input boxes, and then click buttons to execute
programs that perform DB functions.
• We will use the following utilities:
– Form builder
– Report builder
• To use these utilities effectively an understanding of
PL/SQL is needed.
• PL/SQL is a procedural programming language that
Oracle utilities use to manipulate DB data.
• Programming or scripting language concepts
understanding is necessary.
Guide to Oracle 10g 3
Fundamentals of PL/SQL
• PL/SQL program combines SQL queries with
procedural commands (if/then, loops).
• It is a full-featured programming language
• Executed using Oracle 10g utilities such as:
– SQL*Plus or
– Forms Builder
• It is an interpreted language
• Its commands are not case sensitive. Inside single
quotes are case sensitive.. „M‟ != „m‟
• Semicolon ends each command
• It contains reserved words and built in functions.
Guide to Oracle 10g 4
PL/SQL Command Capitalization
Styles

Guide to Oracle 10g 5


PL/SQL Variables and Data Types

• Variable names must follow the Oracle naming


standard
• Strongly typed language:
– Explicitly declare each variable including data type
before using variable
• Variable declaration syntax:
– variable_name data_type_declaration;
• Default value always NULL
• PL/SQL supports: scalar, composite, reference and
LOB.
Guide to Oracle 10g 6
Scalar Variables

• Reference single value


• Data types correspond to Oracle 10g database data
types
– VARCHAR2
– CHAR
– DATE
– NUMBER

Guide to Oracle 10g 7


General Scalar Data Types

Guide to Oracle 10g 8


Composite Variables
• Data Structure is a data object made up of multiple
individual data elements
• Composite variable is a data structure contains
multiple scalar variables
• Types:
– RECORD
– TABLE
– VARRAY

Guide to Oracle 10g 9


Reference Variables
• Reference variables directly reference specific
database column or row
• Reference variables assume data type of associated
column or row
• %TYPE data declaration syntax:
– variable_name
tablename.fieldname%TYPE;
• %ROWTYPE data declaration syntax:
– variable_name tablename%ROWTYPE;

Guide to Oracle 10g 10


Reference Variables
• The (%TYPE) reference data type specifies a
variable that references a single DB field.
– current_f_last FACULTY.F_LAST%TYPE;

• The current_f_last variable assumes a data type of


VARCHAR2(30), because this is the data type of
the f_last column in the FACULTY table.

Guide to Oracle 10g 11


Reference Variables
• The (%ROWTYPE) reference data type creates
composite variables that reference the entire data
record.
– Faculty_row FACULTY%ROWTYPE;

• The variable faculty_row references all of the


columns in the FACULTY table, and each column
has the same data type as its associated DB column.

Guide to Oracle 10g 12


LOB Data Types
• It declares variables that reference binary or
character data objects up to 4 GB.

• LOB values in PL/SQL programs must be


manipulated using special package called
DBMS_LOB.

Guide to Oracle 10g 13


PL/SQL Program Blocks

• Declaration section (DECLARE)


– Optional (variable declaration)
• Execution section (BEGIN)
– Required (Program statements)
• Exception section (EXCEPTION)
– Optional (Error handling statements)
• Comment statements
– Enclosed within /* and */
– Two hyphens (--) for a single line comment
• END;

Guide to Oracle 10g 14


PL/SQL Arithmetic Operators in
Describing Order of Precedence

Guide to Oracle 10g 15


Assignment Statements

• Assigns value to variable


• Operator
– :=
• Syntax
– variable_name := value;
• String literal must be enclosed in a single
quotation marks.

Guide to Oracle 10g 16


Assignment Statements
• You can use the := in the declaration section to
give initial values.
– s_id NUMBER := 100;

• You can use DEFAULT instead:


– s_id NUMBER DEFAULT 100;

• If NULL value is used in an assignment statement


with arithmetic operation, the result is always
NULL.
Guide to Oracle 10g 17
Executing a PL/SQL Program in
SQL*Plus
• Create and execute PL/SQL program blocks
within variety of Oracle 10g development
environments:
– SQL *Plus
– Form Builder
– Report Builder

Guide to Oracle 10g 18


Displaying PL/SQL Program Output in SQL*Plus

• PL/SQL output buffer


– Memory area on database server
– Stores program‟s output values before they are
displayed to user
– Buffer size should be increased before output is
displayed:
• SET SERVEROUTPUT ON SIZE buffer_size
– Default buffer size
• 2000 bytes
– If the output is more than buffer_size, error apperas.

Guide to Oracle 10g 19


Displaying PL/SQL Program Output in SQL*Plus
(continued)
• Display program output
– DBMS_OUTPUT.PUT_LINE('display_text');
– Display maximum of 255 characters of text data.
– More than 255 characters gives an error.
• Example:
– s_name := „Ahmed Mahmoud‟;
– DBMS_OUTPUT.PUT_LINE(s_name);

Guide to Oracle 10g 20


Writing a PL/SQL Program

• Write PL/SQL program in Notepad or another text


editor
• Copy and paste program commands into SQL*Plus
• Press Enter after last program command
• Type front slash ( / ) (to instruct the interpreter to execute the code)
• Then press Enter again

Guide to Oracle 10g 21


Writing a PL/SQL Program
(continued)
• Good programming practice
– Place DECLARE, BEGIN, and END commands
flush with left edge of text editor window
– Indent commands within each section

Guide to Oracle 10g 22


PL/SQL Program Commands

Output: Today‟s data is


18-OCT-07
PL/SQL procedure successfully completed

• If no output appears use: SQL> set serveroutput on


Guide to Oracle 10g 23
PL/SQL Data Conversion Functions

• Implicit data conversions


– Interpreter automatically converts value from one data
type to another (the command DBMS_OUTPUT.PUT_LINE(todays_date), the
interpreter automatically converted the todas_date DATE variable to a text string for
output).

– If PL/SQL interpreter unable to implicitly convert value


error occurs
• Explicit data conversions
– Convert variables to different data types
– Using built in data conversion functions

Guide to Oracle 10g 24


PL/SQL Data Conversion Functions of
PL/SQL

Guide to Oracle 10g 25


Manipulating Character Strings with
PL/SQL
• String
– Character data value
– Consists of one or more characters
• Concatenating
– Joining two separate strings
• Parse
– Separate single string consisting of two data items
separated by commas or spaces
• Built in functions to concatenate and parse strings
in SQL*Plus are as follows:

Guide to Oracle 10g 26


Concatenating Character Strings

• Double bar Operator


– ||
• Syntax:
– new_string := string1 || string2;
• Example:
– Full_name := ‘Qusai’ || ‘ ‘ || ‘Abuein’

• You must convert NUMBER and DATE data


type variables (TO_CHAR)into a string
before concatenating it.
Guide to Oracle 10g 27
Removing Blank Leading and Trailing
Spaces from Strings
• LTRIM function
– Remove blank leading spaces
– string := LTRIM(string_variable_name);
• RTRIM function
– Remove blank trailing spaces
– string := RTRIM(string_variable_name);

Guide to Oracle 10g 28


Finding the Length of Character
Strings
• LENGTH function syntax

– string_length := LENGTH(string_variable_name);

• Space is included wherever it appears.


– DBMS_OUTPUT.PUT_LINE(LENGTH('Today''s date is '));
– Gives 20.

Guide to Oracle 10g 29


Character String Case Functions

• Modify case of character strings


• Functions and syntax:
– string :=
UPPER(string_variable_name);
– string :=
LOWER(string_variable_name);
– string :=
INITCAP(string_variable_name);

Guide to Oracle 10g 30


Parsing Character Strings
• INSTR function
– Searches string for specific substring
– If substring is found, the starting position of it
within the original_string is returned as integer
value. Otherwise, zero is returned.
– Syntax:
• start_position :=
INSTR(original_string, substring);
– start_positioin should be integer
data type.

Guide to Oracle 10g 31


Parsing Character Strings

• SUBSTR function
– Extracts specific number of characters from character
string starting at given point
– Syntax:
• extracted_string := SUBSTR(string_variable,
starting_point, number_of_characters);
• To parse a string, usually INSTR is used to find delimiter and then use the
SUBSTR.

Guide to Oracle 10g 32


Ex. Pg 207

Figure 4-7 33
Debugging PL/SQL Programs

• Syntax error
– Occurs when command does not follow guidelines
of programming language
– Generate compiler or interpreter error messages
• Logic error
– Does not stop program from running
– Results in incorrect result

Guide to Oracle 10g 34


Program with a Syntax Error

Guide to Oracle 10g 35


Program with a Logic Error

Guide to Oracle 10g 36


Finding Syntax Errors

• Often involve:
– Misspelling reserved word
– Omitting required character in command
– Using built-in function improperly
• Interpreter
– Flags line number and character location of syntax
errors
• May actually be on preceding line
– Displays error code and message
Guide to Oracle 10g 37
Finding Syntax Errors (continued)

• Comment out program lines


– To find error
• Cascading errors are called so when
– One syntax error can generate many more errors
– Fix the first error and rerun the program. Do not fix
next errors before rerunning the program.

Guide to Oracle 10g 38


Finding Logic Errors

• Caused by:
– Not using proper order of operations in arithmetic
functions
– Passing incorrect parameter values to built-in
functions
– Creating loops that do not terminate properly
– Using data values that are out of range or not of
right data type

Guide to Oracle 10g 39


Finding Logic Errors (continued)

• Debugger
– Program that enables software developers to pause
program execution and examine current variable
values
– Best way to find logic errors
– SQL*Plus environment does not provide PL/SQL
debugger
– Use DBMS_OUTPUT to print variable values

Guide to Oracle 10g 40


Lesson A Summary
• PL/SQL data types:
– Scalar
– Composite
– Reference
– LOB
• Program block
– Declaration
– Execution
– Exception
Guide to Oracle 10g 41
Lesson B Objectives
After completing this lesson, you should be able to:
• Create PL/SQL decision control structures
• Use SQL queries in PL/SQL programs
• Create loops in PL/SQL programs
• Create PL/SQL tables and tables of records
• Use cursors to retrieve database data into PL/SQL
programs

Guide to Oracle 10g 42


Lesson B Objectives (continued)

• Use the exception section to handle run-time errors in


PL/SQL programs

Guide to Oracle 10g 43


PL/SQL Decision Control Structures

• Sequential processing
– Processes statements one after another
• Decision control structures
– Alter order in which statements execute
– Based on values of certain variables

Guide to Oracle 10g 44


IF/THEN

• Syntax:
IF condition THEN
commands that execute if condition
is TRUE;
END IF;
• Condition
– Expression evaluates to TRUE or FALSE
– If TRUE commands execute
– See Examples pages 221,222

Guide to Oracle 10g 45


• Declare
– todays_date DATE;
– current_day varchar2(9);
• Begin
– todays_date := sysdate;
– current_day := to_char(todays_date, „DAY‟);
– current_day := initcap(current_day);
– current_day := rtrim(current_day);
– If current_day = „Friday‟ then
Dbms_output.put_line(„Today is Friday‟);
– End if;
• End;
• /
• PL/SQL procedure successfully completed

Guide to Oracle 10g 46


PL/SQL Comparison Operators

Do not get confused with the equal (=) sign and the assignment (:=) operator
Guide to Oracle 10g 47
IF/THEN/ELSE
• Syntax:
IF condition THEN
commands that execute if condition
is TRUE;
ELSE
commands that execute if condition
is FALSE;
END IF;
• Evaluates ELSE command if condition FALSE
• See example pages 223
Guide to Oracle 10g 48
• Declare
– todays_date DATE;
– current_day varchar2(9);
• Begin
– todays_date := sysdate;
– current_day := to_char(todays_date, „DAY‟);
– current_day := initcap(current_day);
– current_day := rtrim(current_day);
– If current_day = „Friday‟ then
Dbms_output.put_line(„Today is Friday‟);
– Else
Dbms_output.put_line(„Today is not Friday‟);
– End if;
• End;
• /
Today is not Friday
• PL/SQL procedure successfully completed
Guide to Oracle 10g 49
Nested IF/THEN/ELSE

• Placing one or more IF/THEN/ELSE statements


within program statements that execute after IF or
ELSE command
• Important to properly indent program lines
• See example page 224

Guide to Oracle 10g 50


• Declare
– todays_date DATE;
– current_day varchar2(9);
• Begin
– todays_date := sysdate;
– current_day := to_char(todays_date, „DAY‟);
– current_day := initcap(current_day);
– current_day := rtrim(current_day);
– If current_day = „Friday‟ then
Dbms_output.put_line(„Today is Friday‟);
– Else
If current_day = „Saturday‟ then
Dbms_output.put_line(„Today is Saturday‟);

Else
Dbms_output.put_line(„Today is not Friday or Saturday‟);

End if;
– End if;
• End;
• /
Today is not Friday or Saturday
• PL/SQL procedure successfully completed 51
IF/ELSIF
• Syntax:
IF condition1 THEN
commands that execute if condition1 is TRUE;
ELSIF condition2 THEN
commands that execute if condition2 is TRUE;
...
ELSE
commands that execute if no conditions TRUE;
END IF;

• Note there is no second E in ELS and no space


between ELS and IF.
• See example page 225

Guide to Oracle 10g 52


• Declare
– todays_date DATE;
– current_day varchar2(9);
• Begin
– todays_date := sysdate;
– current_day := to_char(todays_date, „DAY‟);
– current_day := initcap(current_day);
– current_day := rtrim(current_day);
– If current_day = „Friday‟ then
Dbms_output.put_line(„Today is Friday‟);
– Elsif current_day = „Saturday‟ then
dbms_output.put_line(„Today is Saturday‟);
– Elsif current_day = „Sunday‟ then
dbms_output.put_line(„Today is Sunday‟);
– Else
dbms_output.put_line(„Today is not Friday or Saturday or Sunday‟);
– End if;
• End;
• /
Today is not Friday or Saturday or Sunday 53

• PL/SQL procedure successfully completed


Logical Operators AND, OR, and
NOT
• Create complex expressions for decision control
structure condition
• AND
– Expressions on both sides of operator must be true
for combined expression to be TRUE
• OR
– Expressions on either side of operator must be true
for combined expression to be TRUE

Guide to Oracle 10g 54


Logical Operators AND, OR, and
NOT (continued)
• Order of evaluation:
– NOT (evaluated first)
– AND
– OR

Guide to Oracle 10g 55


Evaluating AND and OR in an
Expression

Guide to Oracle 10g 56


Using SQL Queries in PL/SQL Programs

• Use SQL action query


– Put query or command in PL/SQL program
– Use same syntax as you execute query or command in
SQL*Plus
– Can use variables instead of literal values to specify
data values
• Ex: curr_f_name := “Ahmad‟
• We need to insert „Ahmad‟ into a column S_FIRST
• INSERT INTO student (s_first)
• VALUES (curr_f_name); PL/SQL Command
– Ex: WHERE s_first = curr_f_name;
Guide to Oracle 10g 57
Using SQL Commands in PL/SQL
Programs

Guide to Oracle 10g 58


Loops
• Systematically executes program statements
• Periodically evaluates exit condition to determine
if loop should repeat or exit
• Pretest loop
– Evaluates exit condition before any program
commands execute
• Posttest loop
– Executes program commands before loop evaluates
exit condition for first time
• In PL/SQL there are FIVE loop structures.

Guide to Oracle 10g 59


The LOOP...EXIT Loop
• This kind of loop can be either Pretest or posttest
• Syntax:
LOOP
[program statements]
IF condition THEN
EXIT;
END IF;
[additional program statements]
END LOOP;

Guide to Oracle 10g 60


The LOOP...EXIT Loop

• LOOP keyword signals the beginning of the loop.



• If the IF/THEN decision structure is the first code
in the loop, it is a pretest loop.

• If the IF/THEN decision structure is the last code


in the loop, it is a posttest loop.

• See Example page 233.

Guide to Oracle 10g 61


Declare
loop_count binary_integer :=1;
Begin
Loop
insert into count_table values(loop_count);
loop_count := loop_count + 1;
if loop_count = 6 then
Exit;
End if;
End Loop;
End;
/
PL/SQL procedure successfully completed.
Select * from count_table;
Counter
1
2
3
4
5 62
The LOOP...EXIT WHEN Loop

• Can be either a Pretest or posttest


• Syntax:
LOOP
program statements
EXIT WHEN condition;
END LOOP;

• See example page 234.


Guide to Oracle 10g 63
Declare
loop_count binary_integer :=1;
Begin
delete from count_table;
-- delete all table records
Loop
insert into count_table values(loop_count);
loop_count := loop_count + 1;
Exit when loop_count = 5;
End Loop;
End;
/
PL/SQL procedure successfully completed.
Select * from count_table;
Counter
1
2
3
4
64
The WHILE...LOOP

• It is a Pretest loop that test the condition before it


execute any program statements.
• Syntax:
WHILE condition LOOP
program statements
END LOOP;

• See example page 235.

Guide to Oracle 10g 65


Declare
loop_count binary_integer :=6;
Begin
delete from count_table;
-- delete all table records
While loop_count < 11 Loop
insert into count_table values(loop_count);
loop_count := loop_count + 1;
End Loop;
End;
/
PL/SQL procedure successfully completed.
Select * from count_table;
Counter
6
7
8
9
10
66
The Numeric FOR Loop
• In the previous LOOP structures we had to
increment the counter variable.
• The numeric FOR does not require explicit
counter increment
– Automatically increments counter
• Syntax:
FOR counter_variable IN start_value ... end_value
LOOP
program statements
END LOOP;
• Start_value and end_value must be integer. The increment is always done
by 1. See example page 236.
Guide to Oracle 10g 67
Begin
delete from count_table;
-- delete all table records
For loop_count IN 1..5
LOOP
insert into count_table values(loop_count);
End Loop;
End;
/
PL/SQL procedure successfully completed.
Select * from count_table;
Counter
1
2
3
4
5

68
Cursors

• Pointer to memory location on database server that


the DBMS uses to process a SQL query
• Use to:
– Retrieve and manipulate database data from the
tables into PL/SQL programs
• Types:
– Implicit
– Explicit

Guide to Oracle 10g 69


Implicit Cursors
• Context area
– Is a memory location on the DB server contains
information about query, such as the number of rows
the query processed.
– Created by INSERT, UPDATE, DELETE, or SELECT
• Active set
– Set of data rows that query retrieves using SELECT
• Implicit cursor
– Is a Pointer to the context area.
– Called so because you do not need explicit command to
create it.

Guide to Oracle 10g 70


Implicit Cursors (continued)

• Can be used to assign output of SELECT query to


PL/SQL program variables:
– When query returns only one record
– If the query returns more than one record or zero
records, an error occurs.

Guide to Oracle 10g 71


Implicit Cursors (continued)
• Syntax:
SELECT field1, field2, ...
INTO variable1, variable2, ...
FROM table1, table2, ...
WHERE join_conditions
AND search_condition_to_retrieve_1_record;

• The value of field1 is assigned to variable1, field2


to variable2 and so on.

• Data types of field1, field2 and variable1, variable2


must be the same.

Guide to Oracle 10g 72


Implicit Cursors (continued)
• Useful to use %TYPE reference data type
– To declare variables used with implicit cursors
– Syntax: var_name tablename.fieldname%TYPE
– Ex: curr_f_last faculty.f_last%TYPE
– Ex: Page 239 (fig. 4-26)
• Declare
– Current_f_last faculty.f_last%TYPE;
– Current_f_first faculty.f_first%TYPE;
• Begin
– SELECT f_last, f_first
– INTO current_f_last, current_f_first
– From faculty
– Where f_id = 1;
– Dbms_output.put_line(„The faculty member‟‟s name is „ || current_f_first || „ „ ||
current_f_last;
• End;
Guide to Oracle 10g 73
• The faculty member‟s name is Teresa Marx
• In last example If the select statement had the following
condition that would return more than one record:
• Where f_first LIKE „J%‟
• Error “ORA-01422: exact fetch returns more than
requested number of rows” . Ex. Page 239 (fig. 4-27).
– Implicit cursor query tried to retrieve multiple records
• In last example If the select statement had the following
condition that would return no records:
• Where f_id = 6 (table has f_id’s upto 5)
• Error “ORA-014032: no data found. Ex. Page 240 (fig.4-
28).
• If one of these errors occur, you should modify the query
to retrieve only one record, or use Explicit cursor.
Guide to Oracle 10g 74
Explicit Cursors

• Retrieve and display data in PL/SQL programs for


query that might:
– Retrieve multiple records
– Return no records at all
• Steps for creating and using explicit cursor
– Declare cursor
– Open cursor
– Fetch data rows
– Close cursor

Guide to Oracle 10g 75


Explicit Cursors (continued)
• Declare explicit cursor syntax: by declaring an explicit cursor, you create a
memory location on the DB server that processes a query and stores the retrieved records .
– Syntax:
– CURSOR cursor_name IS select_query;
• cursor_name: Any valid PL/SQL name.
• select_query: The query that retrieves the data values.

• Open explicit cursor syntax: by doing so the interpreter checks for syntax
errors and translates the query into machine-language format. The system then creates the
memory location that stores the active set (contains the retrieved data using SELECT).
– Syntax
– OPEN cursor_name;

Guide to Oracle 10g 76


Explicit Cursors (continued)
• Fetch command is used to retrieve the data from the DB into the active set, one row
at a time.
• Because a query might return several rows, you execute the
FETCH command within a (LOOP…EXIT WHEN) loop:
• Syntax:
LOOP
FETCH cursor_name INTO
variable_name(s);
EXIT WHEN cursor_name%NOTFOUND;

• Cursor_name is name of the cursor defined previously.


• Variable_name(s) represents either a single variable or a list of variables that receives
data from the cursor‟s SELECT query. (every retrieved column from the DB table is
associated with a program variable variable, %TYPE or %ROWTYPE)

Guide to Oracle 10g 77


Explicit Cursors (continued)

• Active set pointer is created when processing explicit


cursor that:
– Indicates memory location of the next record retrieved
from database
– After the last record of the query is executed, that
pointer points to an empty record.
– The condition (EXIT WHEN cursor_name%NOTFOUND)
guarantees the exit when the pointer points to an empty
record.

Guide to Oracle 10g 78


Explicit Cursors (continued)
• Close cursor syntax:
– CLOSE cursor_name;

• You should close a cursor after


processing all records so as the memory
and other resources are available to
the system for other tasks.

• The system automatically closes the


cursor when the program ends, if you
forget to do so.

Guide to Oracle 10g 79


Processing Explicit Cursors Using a
LOOP...EXIT WHEN Loop
• Often used to process explicit cursors that retrieve and display
database records
• Use %TYPE variable to display explicit cursor values (See example
Figure 4-29 page 243)

Guide to Oracle 10g 80


Figure 4-29 page 243
• Declare
– Current_bldg_code VARCHAR2(5);
– CURSOR location_cursor IS
• Select room from location where bldg_code = current_bldg_code;
– Current_room location.room%TYPE;
• Begin
– Current_bldg_code := „LIB‟;
– Open location_cursor;
– Loop
• Fetch location_cursor INTO current_room;
• EXIT WHEN location_cursor%NOTFOUND;
• Dbms_output.put_line(„The current room is „|| current_bldg_code || „ „ ||
current_room);
– End loop;
– Close location_cursor;
• End;
• The current room is LIB 217 81
• The current room is LIB 222
Use %ROWTYPE variable to display explicit cursor values (See
example Figure 4-30 page 244)
• Declare
– Current_bldg_code VARCHAR2(5);
– CURSOR location_cursor IS
• SELECT room, capacity FROM location WHERE bldg_code =
current_bldg_code;
– location_row location_cursor%ROWTYPE;
• Begin
– Current_bldg_code := „LIB‟;
– Open location_cursor;
– Loop
• Fetch location_cursor INTO current_room;
• EXIT WHEN location_cursor%NOTFOUND;
• DBMS_OUTPUT.PUT_LINE(„The capacity of „ || current_bldg_code || „ „ ||
location_row.room || „ is „ || location_row.capacity || „ Seat(s).‟);
– End loop;
– Close location_cursor;
• End;
• The capacity of LIB 217 is 2 Seat(s).
82
• The capacity of LIB 222 is 1 Seat(s).
Processing Explicit Cursors Using a
Cursor FOR Loop
• Makes it easier than LOOP...EXIT WHEN to process
explicit cursors.
• Cursor For Loop automatically:
– Opens cursor
– Fetches records
– Closes cursor

Guide to Oracle 10g 83


Processing Explicit Cursors Using a
Cursor FOR Loop (continued)
• Syntax:
FOR variable_name(s) IN cursor_name
LOOP
processing commands
END LOOP;

• See example Figure 4-31 page 245.

Guide to Oracle 10g 84


• Declare
– Current_bldg_code VARCHAR2(5);
– CURSOR location_cursor IS
• SELECT room, capacity FROM location WHERE bldg_code =
current_bldg_code;
– location_row location_cursor%ROWTYPE;
• Begin
– Current_bldg_code := „LIB‟;
– For location_row IN location_cursor LOOP
• DBMS_OUTPUT.PUT_LINE(„The capacity of „ || current_bldg_code || „ „ ||
location_row.room || „ is „ || location_row.capacity || „ Seat(s).‟);
– End LOOP;
• End;
• /
• The capacity of LIB 217 is 2 Seat(s).
• The capacity of LIB 222 is 1 Seat(s).

Guide to Oracle 10g 85


Explicit Cursors Using a Cursor FOR Loop,
LOOP...EXIT WHEN

• The cursor variable can be referenced


outside the Loop … Exit When. While can
not be referenced outside the For Loop.

Guide to Oracle 10g 86


Handling Runtime Errors in PL/SQL
Programs
• Pl/SQL supports Exception handling, that is:
– Programmers place commands for displaying error messages
and
– Give users options for fixing errors in program‟s exception
section (Optional section in a PL/SQL program block. Page 195)
• Runtime errors
– Cause program to fail during execution
• Exception section is used to handle runtime error.
– Unwanted event.
– See Example Figure 4-32. Page 247 (runtime error).

Guide to Oracle 10g 87


• Declare
– Term_id Binary integer := 1;
– Term_desc varchar2(20) := „Fall 2005‟;
– Term_status varchar2(20) := „closed‟;
– Term_date DATE := „29-aug-05‟;
• Begin
– --insert first record
– INSERT INTO term VALUES (term_id, term_desc, term_status, term_date);
– -- update values and insert other records
– Term_id := term_id + 1;
– Term_desc := „Spring 2006‟;
– Term_date := „09-Jan-06‟;
– INSERT INTO term VALUES (term_id, term_desc, term_status, term_date);
– COMMIT;
• END;
• Declare
• *
• ERROR at line:
• ORA-00001: unique constraint (SYSTEM.term_term_id_pk) violated /*specific
runtime error message*/
• ORA-06512: at line 8 /*error code that signals a runtime error*/
88
Handling Runtime Errors in PL/SQL Programs (cont.)
• An exception or unwanted event is raised when a
runtime error occurs.
• The control is transferred to the exception section,
where the exception handler has the following options:
– Correct error without notifying user of problem
– Inform user of error without taking corrective action
– Correct and inform
– Inform the user and allow him to decide what action to
take.
• After exception handler executes
– Program ends
Guide to Oracle 10g 89
Handling Runtime Errors in PL/SQL Programs (cont.)

• There are three kinds of exceptions:


– Predefined
– Undefined
– User defined

Guide to Oracle 10g 90


Predefined Exceptions
• Most common errors that occur in programs
• PL/SQL language:
– Assigns exception name
– Provides built-in exception handler for each predefined
exception
• System automatically displays error message informing
user of the nature of the problem
• One can create exception handlers to display alternate
error messages for predefined exception

Guide to Oracle 10g 91


Common PL/SQL Predefined
Exceptions

Guide to Oracle 10g 92


Exception Handler Syntax
The syntax to write an alternate error messages for predefined handler.

Guide to Oracle 10g 93


Exception Handler Syntax
• exception_name1, exception_name2,… refer to the
name of the predefined exception (table 4-10).
• Exception handler commands represent commands
that display the error message.
• WHEN OTHERS THEN clause is a catchall handler
presents a general message to describe errors that do
not have specific exception handlers.

• See examples 4-34 and 4-35. Pages 249, 250.

Guide to Oracle 10g 94


• Declare
– Current_course_no varchar2(8) := „CIS 100‟;
– Current_course_name varchar2(20);
• Begin
– Select course_name into current_course_name from course where
course_no = current_course_no;
– Dbms_output.put_line(„the course name is „||
current_course_name);
• END;
• /
• Declare
• *
• Error at line 1:
• ORA-01403: no data found -- predefined exception name
• ORA-06512: at line 5

95
• Declare
– Current_course_no varchar2(8) := „CIS 100‟;
– Current_course_name varchar2(20);
• Begin
– SELECT course_name INTO current_course_name FROM course
WHERE course_no = current_course_no;
– DBMS_OUTPUT.PUT_LINE(„The course name is „||
current_course_name);
• Exception
– When no_data_found then
• DBMS_OUTPUT.PUT_LINE(„Course number „|| current_course_no
|| „is not valid.‟);
• DBMS_OUTPUT.PUT_LINE(„Please specify a valid course
number.‟);
• END;
• /
• Course number CIS 100 is not valid. --Alternate error message
• Please specify a valid course number. 96
Exception Handler Syntax
• When using alternate error message, such as in the example 4-
35, which handles only the NO_DATA_FOUND. An
unanticipated error might occur. That way no handler exists to
handle such unanticipated errors.
• For that reason it is helpful to use the WHEN OTHERS
exception handler too, so as to display messages for that
situation.
• To do this, use SQLERRM built-in function (SQL ERRor
Message).
• That function returns a string that contains the most recent error
code and its description.
• First define a varchar2 variable of length 512 to assign it the
error message: error_message := SQLERRM;
• Guide
Seetoexample
Oracle 10g
Figure 4-36 page 251. 97
• Declare
– Current_course_no varchar2(8) := „CIS 100‟;
– Current_course_name varchar2(20);
– Error_message varchar2(512);
• Begin
– SELECT course_name INTO current_course_name FROM course;
– DBMS_OUTPUT.PUT_LINE(„The course name is „|| current_course_name);
• Exception
– When no_data_found then
• DBMS_OUTPUT.PUT_LINE(„Course number „|| current_course_no || „is not
valid.‟);
• DBMS_OUTPUT.PUT_LINE(„Please specify a valid course number.‟);
– When others then
• Error_message := SQLERRM;
• DBMS_OUTPUT.PUT_LINE(„This program encountered the following error:
„);
• DBMS_OUTPUT.PUT_LINE(error_message);
• END;
• /
• This program encountered the following error: --when others error handler
• ORA-01422: exact fetch returns more than requested number of rows
98
Undefined Exceptions
• Less common errors
• Do not have predefined names
• One must explicitly declare exception in program‟s
declaration section and
• Associate the new exception with a specific Oracle
error code then
• Create an exception handler in the exception section
– Using the same syntax as for predefined exceptions

Guide to Oracle 10g 99


Syntax of Undefined Exceptions
DECLARE
e_exception_name EXCEPTION;
PRAGMA EXCEPTION_INIT(e_exception_name, -Oracle_error_code);
• e-exception_name represents name you assign to the
exception.
• PRAGMA EXCEPTION_INIT: a command associates your
exception name with a specific Oracle error code.
• The hyphen (-) must precede the Oracle_error_code. See for
example Figure 4-37, the code is –2291.

• See example Figure 4-38 on undefined exception, page 253.

Guide to Oracle 10g 100


• Declare
– New_f_id number(6) := 6;
– New_f_last varchar2(30) := „Sloan‟;
– New_f_first varchar2(30) := „Vivian‟;
– New_f_rank varchar2(9) := „Full‟;
– New_f_loc_id number(5) := 60;
• Begin
– Insert into faculty (f_id, f_last, f_first, f_rank, loc_id) values (new_f_id,
new_f_last, new_f_first, new_f_rank, new_f_loc_id);
– COMMIT;
• END;
• /
• Declare
• *
• Error at line 1: --error message does not display an exception name, just error
code and message
• ORA-02291: integrity constraint (SYSTEM.FACULTY_LOC_ID_FK)
violated – parent key not found
• ORA-06512: at line 8
101
• Declare
– New_f_id number(6) := 6;
– New_f_last varchar2(30) := „Sloan‟;
– New_f_first varchar2(30) := „Vivian‟;
– New_f_rank varchar2(9) := „Full‟;
– New_f_loc_id number(5) := 60;
– e_foreign_key_error exception;
– Pragma exception_init (e_foreign_key_error, -2291); --exception
• Begin
– Insert into faculty (f_id, f_last, f_first, f_rank, loc_id) values (new_f_id,
new_f_last, new_f_first, new_f_rank, new_f_loc_id);
– COMMIT;
• Exception – exception handler
– When e_foreign_key_error Then
• Dbms_output.put_line(„Location ID „|| new_f_loc_id || „ does not exist in the
LOCATION table.‟);
• Dbms_output.put_line(„Please specify a valid location ID value‟);
• END;
• Location ID 60 does not exist in the LOCATION table. –output from
exception handler
102
• Please specify a valid location ID value
User-defined Exceptions
• User-defined exceptions do not raise Oracle runtime
error. BUT
• Require exception handling to:
– Enforce business rules ( special rules of a company,
example page 253. Rule: one can only delete grades with
values NULL. Other grades can not be deleted. If a user
tries to delete a grade that its value is not NULL, the
program should raise an exception and display a message )
or
– Ensure the integrity of database

Guide to Oracle 10g 103


General Syntax for Declaring, Raising, and
Handling a User-defined Exception

Guide to Oracle 10g 104


General Syntax for Declaring, Raising, and Handling a User-
defined Exception

• To raise the exception, you must use the IF/THEN,


which evaluates the exception condition (grade IS NOT
NULL).
• If the condition is TRUE, the RAISE command is
executed and raises the exception (transfer execution to
the exception section).
• The exception handler executes and displays the error-
handling messages.

• See example Figure 4-40, page 255.


Guide to Oracle 10g 105
• Declare
– Current_s_id varchar2(6) := „JO100‟;
– Current_c_sec_id Binary_integer := 1;
– current_grade char(1);
– e_null_grade_delete Exception;
• Begin
– Select grade into current_grade from enrollment where s_id = current_s_id and
c_sec_id = current_c_sec_id;
– If current_grade IS NOT NULL Then
• Raise e_null_grade_delete;
– ENDIF;
– --delete the record if exception not raised
– Delete from enrollment where s_id = current_s_id and c_sec_id =
current_c_sec_id;
• Exception
– When e_null_grade_delete Then
• Dbms_output.put_line(„The grade field for the current enrollement record is
not NULL.‟);
• Dbms_output.put_line(„Enrollment record not deleted.‟);
• END;
• The grade field for the current enrollement record is not NULL.
• Enrollment record not deleted.
106
Lesson B Summary

• Decision control structures:


– IF/THEN
– IF/THEN/ELSE
– IF/ELSIF
• Loop
– Repeats action multiple times until it reaches exit
condition
– Five types of loops

Guide to Oracle 10g 107


Lesson B Summary (continued)

• Cursor
– Pointer to memory location that DBMS uses to
process SQL query
– Types:
• Implicit
• Explicit
• Exception handling
– Three exception types

Guide to Oracle 10g 108

You might also like