OCP - SQL&PL - SQL (Vol3)
OCP - SQL&PL - SQL (Vol3)
Edition 1.1
M03991
T1001E11
Authors Copyright EĂOracle Corporation, 1992, 1996. All rights reserved.
All other products or company names are used for identification purposes only,
and may be trademarks of their respective owners.
Publishers
Stephanie Jones
Kimberly Lee
Jennifer Robertson
Mark Turangan
18
Overview of PL/SQL
18Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives
This lesson provides an overview of how to create and use PL/SQL program
units and subprograms using Oracle Procedure Builder.
At the end of this lesson, you should be able to
D Determine the benefits of accessing the Oracle7 database with PL/SQL.
D Describe basic PL/SQL program constructs.
D Describe the Oracle Procedure Builder tool.
What Is PL/SQL?
PL/SQL (Procedural Language/SQL) is an extension to SQL, incorporating many of
the design features of programming languages of recent years. It allows the data
manipulation and query statements of SQL to be included within block-structured and
procedural units of code, making PL/SQL a powerful transaction processing
language.
Benefits of PL/SQLĊcontinued
Portability
D Since PL/SQL is native to Oracle, you can move programs to any host
environment that supports Oracle and PL/SQL.
D You can also move code between the Oracle7 Server and your application
environment using Procedure Builder’s drag-and-drop capabilities.
Integration
D PL/SQL plays a central role to both the Oracle7 Server (through stored
procedures, database triggers, and packages) and Oracle development tools
(through Developer/2000 component triggers).
D Variables and datatypes in PL/SQL and SQL are compatible. Therefore, PL/SQL
bridges the gap between convenient access to database technology and the need
for procedural programming capabilities.
Improve Performance
D PL/SQL can improve the performance of an application. The benefits differ
depending upon the execution environment.
D PL/SQL groups SQL statements together within a single block and sends the
entire block to the server in a single call, therefore reducing network traffic.
Every unit of PL/SQL comprises one or more blocks. These blocks can be entirely
separate or nested one within another. Therefore, one block can represent a small part
of another block, which in turn can be part of the whole unit of code.
Program
Construct Description Availability
Anonymous Block Unnamed PL/SQL block that is All PL/SQL
embedded within an application or environments.
is issued interactively.
Stored Procedure or Named PL/SQL block that can Oracle7 Server with
Function accept parameters and can be Procedural Extension.
invoked repeatedly.
Application Named PL/SQL block that can Components of
Procedure or accept parameters and can be Developer/2000, for
Function invoked repeatedly. example Forms.
Package Named PL/SQL module that Oracle7 Server with
groups together related procedures, Procedural Extension.
functions, and identifiers.
Database Trigger PL/SQL block that is associated Oracle7 Server with
with a database table and is fired Procedural Extension.
automatically.
Application Trigger PL/SQL block that is associated Components of
with an application event and is Developer/2000, for
fired automatically. example Forms.
The two types of constructs covered in this course are anonymous blocks and
subprograms.
Anonymous Blocks
Anonymous blocks are unnamed blocks. They are declared at the point in an
application where they are to be executed and are passed to the PL/SQL engine for
execution at runtime. You can embed an anonymous block within a precompiler
program and within SQL*Plus or Server Manager. Triggers in Developer/2000
components consist of such blocks.
Subprograms
Subprograms are named PL/SQL blocks. You can declare them either as procedures
or as functions. Procedures perform actions, and functions return values.
Developer/2000 components allow you to declare procedures and functions as part of
the application (a form or report), and call them from other procedures, functions, and
triggers.
A key feature of procedural programming is the ability to create and debug code
quickly and easily. Procedure Builder provides all of the functionality necessary
for you to successfully develop and debug PL/SQL programs. This lesson
enables you to manipulate PL/SQL code using Procedure Builder.
At the end of this lesson, you should be able to
D Identify the advantages of developing and debugging PL/SQL programs in
Procedure Builder.
D Manage program units by using the Object Navigator.
D Execute program units and SQL statements by using the PL/SQL Interpreter.
D Define and compile procedures by using the Program Unit editor.
D Define and compile database procedures by using the Stored Program Unit editor.
D Set a breakpoint to suspend program execution.
D Control the execution of an interrupted PL/SQL program unit.
D Test possible solutions by changing variables and procedures at runtime.
Component Description
Object Navigator Manage PL/SQL constructs.
Perform debug actions.
PL/SQL Interpreter Debug PL/SQL code.
Evaluate PL/SQL code in real time.
Program Unit Editor Create and edit PL/SQL source code.
Stored Program Unit Create and edit server-side PL/SQL source code.
Editor
Database Trigger Editor Create and edit database triggers.
The Interpreter
The Interpreter is the central debugging workspace of Procedure Builder. It is a
two-pane window where you display, debug, and run PL/SQL program units. It also
interactively supports the evaluation of PL/SQL constructs, SQL commands, and
Procedure Builder commands.
Online Help
Oracle Procedure Builder has a help facility that provides assistance at any time
during your session. You can access it from the menu bar.
Organizing PL/SQL
Step through application partitioning between the client and server, including using
libraries and moving subprograms between the client and server.
Button Action
Next Card Advance one card.
Back Return to the previous card.
Tell Me Obtain more information about a topic.
Show Me View a short movie or animation on a task.
Options Set Cue Card options.
Exit Exit Cue Cards.
1 5
4
5
2
3 4
4 Expand/collapse/
expand all/collapse all
Element Description
Open Opens a library from the file system or from the Oracle7 Server.
Save Saves a library on the file system or on the Oracle7 Server.
Cut Cuts the selected object and stores it in the clipboard. Cutting an
object also cuts any objects owned by that object.
Copy Makes a copy of the selected object and stores it in the clipboard.
Copying an object also copies any objects owned by that object.
Paste Pastes the cut or copied module into the selected location. Note
that objects must be copied to a valid location in the object
hierarchy.
Create Creates a new instance of the currently selected object.
Delete Deletes the selected object with confirmation.
Expand Expands the first level of subobjects of the currently selected
object.
Collapse Collapses the first level of subobjects of the currently selected
object.
Expand All Expands all levels of subobjects of the currently selected object.
Collapse All Collapses all levels of subobjects of the currently selected object.
Creating a Library
1. Select the Libraries object.
2. Click the Create button.
The new library subobject will appear with a default name.
Saving a Library
1. Select the Library to save.
2. Select Save As from the File menu.
The Save Library dialog box appears.
3. Enter a new name for the library (optional). Choose either the File System or the
Database radio button. Click the OK button to accept the options.
Expanding a Node
1. Select a valid node.
2. Click the Expand button or the Expand All button.
Interpreter Components
Component Description
Program execution buttons Enables you to execute the Step Into, Step Over, Step
Out, Go, and Reset buttons.
Close button Closes the Interpreter.
Source pane Displays a read-only copy of the program unit
currently selected.
Interpreter pane Provides a command line interface to PL/SQL and
Procedure Builder.
Scroll bar Scrolls the window.
Split bar Changes the relative amount of space occupied by each
pane in the Interpreter.
Syntax
1
2
1 Compile and Source 2 Name drop down list 3 Source Text pane
Text maintenance
buttons
4 Compilation Message
pane
Component Description
Compile button Compiles the program unit appearing in the Source
Text pane.
Apply button Saves any changes made to the program unit in the
editor since it was first opened or since the last apply
or revert operation.
Revert button Restores the state of the program unit to the last apply
or revert.
New button Invokes the New Program Unit dialog box.
Delete button Deletes the current program unit (with confirmation).
Name drop down list Displays the name and type of the current program
unit. You can use the drop down list to select another
program unit to edit.
Source Text pane Allows you to enter and edit PL/SQL program unit
source text.
Compilation Message Displays error messages generated as a result of
pane compilation.
1 4
Component Description
Owner drop down list Displays usernames whose stored program units
you can access.
Source Text pane Allows you to enter and edit PL/SQL stored
program unit source text.
Compilation Message pane Displays error messages generated as a result of
compilation.
Name drop down list Displays a list of the owner’s stored program
units.
Save button Compiles and saves the program unit to the
Oracle7 Server.
Setting a Breakpoint
1. Double-click the executable line of code on which to break.
A “B(n)” is placed in the line where the break is set.
2. The message “Breakpoint #n installed at line i of name” is shown in the
Interpreter pane.
Note: Breakpoints also can be set using debugger commands in the Interpreter pane.
Test breakpoints by typing the program unit name at the Interpreter PL/SQL
prompt.
1 Trigger 2 Subprograms
Command Description
Step Into Advances execution into the next executable line of code.
Step Over Bypasses the next executable line of code and advances to the
subsequent line.
Step Out Resumes to end of current level of code, such as the subprogram.
Go Resumes execution until either the program unit ends or is interrupted
again due to a debug action.
Reset Aborts execution at the current debug levels.
1
2
1 Click the Stack node 2 Click the variable value 3 Enter the new value
(debug1)PL/SQL> debug.seti(’I’,3);
4. Click the Go button to resume execution through the end of the program unit.
Note: Variables and parameters can also be changed using commands at the
Interpreter PL/SQL prompt.
Application Partitioning
D Manage program units using the Object Navigator.
D Move program units between client and server.
Editors
D Create and compile procedures by using the Program Unit editor.
D Create and compile database procedures by using the Store Program Unit editor.
Execution Environment
D Execute program units by using the PL/SQL Interpreter.
Debugging
D Suspend program execution by using breakpoints.
D Step through code to determine the location of the error.
D Examine local variables to determine the cause of the error.
D Modify variable values to test possible solutions at runtime.
Practice Contents
D Exploring Procedure Builder menus and windows
D Creating a program unit
D Executing a program unit
PL/SQL> count_loops(4);
PROCEDURE my_message IS
BEGIN
TEXT_IO.PUT_LINE (’Hello World’);
END;
PL/SQL> my_message;
Modularity allows you to break your code into manageable, well-defined logical
units. Each of these units in PL/SQL is called a program unit, or a subprogram.
PL/SQL has two types of subprograms called procedures and functions. This
lesson covers the structure of subprograms and how to invoke them.
At the end of this lesson, you should be able to
D Determine the types of program units and where to use them.
D Explain the differences between and benefits of procedures and functions.
D Develop subprograms.
D Invoke subprograms from Procedure Builder.
Guidelines
D SQL*Plus is another development environment for writing and for initial testing
of a procedure, although you will need to test the procedure by invoking it from
an application.
D The SQL commands issued to create a stored subprogram are CREATE
PROCEDURE or CREATE FUNCTION.
D The SQL commands issued to remove a stored subprogram are DROP
PROCEDURE or DROP FUNCTION.
D Use CREATE OR REPLACE PROCEDURE or CREATE OR REPLACE
FUNCTION so you do not have to issue a DROP statement.
Syntax
PROCEDURE name
[(parameter,...)]
IS
pl/sql_block;
Syntax
Guidelines
D Start the PL/SQL block with the keyword IS.
D Enter any local declarations between IS and BEGIN.
When creating the procedure from Procedure Builder, the CREATE OR REPLACE
portion of the syntax is implied. Therefore, when creating the procedure from
SQL*Plus, begin the statement with CREATE OR REPLACE.
Procedural Parameters
Transfer values to and from the calling environment through parameters. There are
two types that you use. When declaring a procedure, the formal parameter is used to
define the values used in the executable portion of the PL/SQL block. The actual
parameter, or argument, is referenced when invoking a subprogram.
Example
Update the salary of the specified employee to the specified amount through a
procedure.
PROCEDURE change_salary
(v_emp_id IN NUMBER, -- formal parameters
v_new_salary IN NUMBER)
IS
BEGIN -- begin PL/SQL block
UPDATE s_emp
SET salary = v_new_salary
WHERE id = v_emp_id;
COMMIT;
END change_salary;
This procedure, when invoked, will take the parameters for the employee number and
the new salary, and update the salary for that specified employee.
The content of the PL/SQL block will be covered in the lesson “Developing a Simple
PL/SQL Block.”
SQL Functions
There are both user-defined functions, covered in this lesson, and SQL functions. You
are already familiar with SQL functions. You call the function with actual parameters
from within a SQL command, such as SELECT.
Syntax
FUNCTION name
[(parameter,...)]
RETURN datatype
IS
pl/sql_block;
Example
Return the tax based on the value parameter in a function.
FUNCTION tax
(v_value IN NUMBER)
RETURN NUMBER
IS
BEGIN
RETURN (v_value * .07);
END tax;
Avoid using the OUT and IN OUT modes with functions. Functions are designed to
return a single value.
Example
Use the CHANGE_SALARY procedure to change the salary to 1000 for employee
number 17.
Note: You may want to confirm the changes by issuing a SELECT statement.
Syntax
CREATE variable
After creating the variable, you execute the function. Finally, you view the variable
value.
Example
Display the tax based on a value. Use the TAX function created earlier.
Advantages
D Permit calculations that are too complex, awkward, or unavailable with SQL.
D Increase efficiency of queries by performing functions in the server rather than in
an application.
Note: This feature is only available with PL/SQL 2.1 or higher and Oracle7 Server
release 7.1 or higher.
Guidelines
D Only stored functions can be called from SQL statements, procedures cannot.
D The function acts as a single-row function.
D The function cannot contain a DML statement—the function cannot modify
database tables.
D All formal parameters must be IN parameters; none can be an OUT or IN OUT
parameter.
D Datatypes used in the function must be Oracle7 Server internal datatypes, such as
CHAR and DATE, not PL/SQL datatypes, such as BOOLEAN or RECORD.
D The RETURN datatype must be an Oracle7 Server internal datatype.
D You must own or have EXECUTE privileges on the PL/SQL function in order to
call it.
Calling a Function
You can call functions from any of these SQL clauses.
D The select list of a SELECT command
D The condition of a WHERE and HAVING clause
D The CONNECT BY, START WITH, ORDER BY, and GROUP BY clauses
D The VALUES clause of the INSERT command
D The SET clause of the UPDATE command
Example
Use the TAX function to calculate the tax on the total sale for order number 100.
Practice Contents
D Creating a simple procedure
D Debugging the procedure
D Executing the procedure
Note: You use the TEXT_IO built-in package in this procedure to print a result at
the Interpreter prompt.
a.
b.
c.
d.
6. Create a procedure called MY_PROCEDURE to output the phrase “My
Procedure Works” to the screen.
a. Replace the skeleton text with text from LABS/p20proc.pls.
b. Compile the code. Make appropriate corrections so code successfully
compiles.
c. Execute the procedure at the Interpreter prompt.
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.
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.
Syntax
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.”
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.”
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.
Declare a constant for the tax rate, which never changes throughout the PL/SQL
block.
Declare a flag to indicate whether a piece of data is valid or invalid, and initialize the
variable to TRUE.
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.
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.
Syntax
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.
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.
Syntax
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.
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.
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.
Nested Blocks
One of the advantages PL/SQL has over SQL is the ability to nest statements. You
can nest blocks wherever an executable statement is allowed, thus making the nested
block a statement. Therefore, you can break down the executable part of a block into
smaller blocks. The exception section can also contain nested blocks.
Variable Scope
The scope of an object is the region of the program that can refer to the object. You
can reference the declared variable within the executable section.
An identifier is visible in the block in which it is declared and all nested sub-blocks,
procedures, and functions. If the block does not find the identifier declared locally, it
looks up to the declarative section of the enclosing (or parent) blocks. The block
never looks down to enclosed (or child) blocks or sideways to sibling blocks.
Scope applies to all declared objects, including variables, cursors, user-defined
exceptions, and constants.
Syntax
identifier := expr;
plsql_table_name(primary_key_value) := expr;
plsql_record_name.field_name := expr;
Examples
Set the maximum salary identifier V_MAX_SAL to the value of current salary
identifier V_SAL.
v_max_sal := v_sal;
Store the name “Maduro” in the index identifier of 3 in the PL/SQL TABLE of last
names.
emp_record.last_name := ’Maduro’;
emp_record.first_name := ’Elena’;
emp_record.gender := ’F’;
Set the salary to the salary from the S_EMP table. This example produces a compile
error.
v_sal := s_emp.salary;
Remember that string literals must be enclosed with single quotation marks, for
example, ’Hello, world’. If there is a single quotation mark in the string, write
a single quotation mark twice, for example, ’Account wasn’’t found’.
Class Exercise
Evaluate the PL/SQL block on the opposite page. Determine each of the following
values according to the rules of scoping.
1. The value of V_WEIGHT within the sub-block.
2. The value of V_NEW_LOCN within the sub-block.
3. The value of V_WEIGHT within the main block.
4. The value of V_MESSAGE within the main block.
5. The value of V_NEW_LOCN within the main block.
Operators
The logical, arithmetic, and concatenation operators used in PL/SQL are the same as
those in SQL. In addition, there is an exponential operator (**).
You can control the order in which operations are performed by using parentheses, as
in SQL.
Examples
Increment the index for a loop.
v_count := v_count + 1;
Set the value of a Boolean flag depending upon whether two numbers are equal.
Functions
Most of the functions available in SQL are also valid in PL/SQL expressions:
D Single-row number functions
D Single-row character functions
D Datatype conversion functions
D Date functions
D Miscellaneous functions
Functions not available in procedural statements:
D GREATEST and LEAST
D Group functions: AVG, MIN, MAX, COUNT, SUM, STDDEV, and VARIANCE
Group functions apply to groups of rows in a table, and are therefore available only
within SQL statements in a PL/SQL block.
Examples
Build the mailing address for a company.
v_mailing_address := v_name||CHR(10)||v_address||
CHR(10)||v_country||CHR(10)||v_zip_code;
Compute the sum of all numbers stored in the NUMBER_TABLE PL/SQL table.
This example produces a compile error.
v_total := SUM(number_table);
CHR is the SQL function that converts an ASCII code to its corresponding character;
10 is the code for a line feed.
Datatype Conversion
Within an expression, you should make sure that datatypes are the same. If mixed
datatypes occur in the same expression, you should use the appropriate conversion
function from the list below to convert the data.
Syntax
Examples
Store a value that is composed of the user name and today’s date. This code causes a
syntax error.
To correct the error, convert SYSDATE to a character string with the TO_CHAR
conversion function.
PL/SQL will attempt conversion if possible, but the success will depend upon the
operations being performed. It is good programming practice to explicitly perform
datatype conversions because they can favorably affect performance and remain valid
even with a change in software versions.
Example
Store the annual salary in a SQL*Plus global variable.
Guidelines
D Document code with comments.
D Develop case conventions for the code.
D Develop naming conventions for identifiers and other objects.
D Indent code to enhance readability.
Commenting Code
Comment code to document each phase and to assist with debugging. Comment the
PL/SQL code with two dashes (--) if the comment is on a single line, or enclose the
comment between the symbols /* and */ if the comment spans several lines.
Example
Compute the yearly salary from the monthly salary.
...
v_sal NUMBER(9,2);
BEGIN
/* Compute the annual salary based on the monthly
salary input from the user */
v_sal := v_sal*12;
END;
Code Conventions
A set of guidelines for writing code in uppercase or lowercase helps you to
distinguish keywords from named objects.
Indentation
For clarity, indent each level of code. This enhances readability.
...
BEGIN
IF x=0 THEN
y=1;
END IF;
...
END;
PL/SQL Blocks
D Declaration section: optional
D Executable section: required
D Exception handling section: optional
PL/SQL Identifiers
D Identifiers are defined in the declaration section.
D Definition can be a scalar datatype with no internal components, such as
NUMBER, VARCHAR2, DATE, and BOOLEAN.
D Definition can be a composite datatype with internal components, such as TABLE
and RECORD.
D Definition can be based on the structure of another variable or a database object
by using %TYPE and %ROWTYPE attributes.
D Identifiers created with NOT NULL or CONSTANT options require initialization.
D When referencing variables, keep in mind the scoping and conversion rules.
Practice Contents
D Determining validity of declarations
D Reviewing scoping and nesting rules
D Developing a simple subprogram in Oracle Procedure Builder
DECLARE
v_id NUMBER (4);
a.
DECLARE
v_x, v_y, v_z VARCHAR2(10);
b.
DECLARE
v_birthdate DATE NOT NULL;
c.
DECLARE
v_in_stock BOOLEAN := 1;
d.
DECLARE
emp_record emp_record_type;
e.
DECLARE
TYPE name_table_type IS TABLE OF VARCHAR2(20)
INDEX BY BINARY_INTEGER;
dept_name_table name_table_type;
f.
2. Suppose you embed a sub-block within a block, as depicted below. You declare
two variables, V_CUSTOMER and V_CREDIT_RATING, within the main block.
You also declare two variables,V_CUSTOMER and V_NAME in the sub-block.
Determine the values for each variable in each case listed below.
a. The value of V_CUSTOMER in the sub-block is
Scope Example
DECLARE
v_customer VARCHAR2(50) := ’Womansport’;
v_credit_rating VARCHAR2(10) := ’EXCELLENT’;
BEGIN
DECLARE SUBĆBLOCK
v_customer
NUMBER (7) := 201;
v_name VARCHAR2(25):= ’Unisports’;
BEGIN
v_customer v_name v_credit_rating
END;
END;
3. Create and execute a procedure named MULTIPLIER that accepts two numbers
through variables. The first number should be divided by the second number and
have the second number added to the result. The result should be written to a
PL/SQL variable and printed to the screen.
In this lesson, you access the database and control transactions through SQL
statements in PL/SQL.
At the end of this lesson, you should be able to
D Use SELECT, INSERT, UPDATE, and DELETE commands in PL/SQL
subprograms.
D Determine the outcome of SQL statements by using implicit cursor attributes.
D Control transactions within PL/SQL.
Abridged Syntax
SELECT select_list
INTO variable_name | record_name
FROM table
WHERE condition;
Guidelines
D Terminate each SQL statement with a semicolon (;).
D Assign values into PL/SQL tables in a loop by declaring an explicit cursor.
D The INTO clause is required for the SELECT statement when it is embedded
within PL/SQL.
D The WHERE clause is optional, and can be used to specify input variables,
constants, literals, or PL/SQL expressions.
Guidelines
D Specify the same number of output variables in the INTO clause as database
columns in the SELECT clause. Be sure that they correspond positionally and that
their datatypes are compatible.
D Ensure that the datatype of the identifiers match the datatype of the columns by
using the %TYPE attribute. The datatype and number of variables in the INTO
clause match those in the SELECT list.
D Terminate the PL/SQL block with the END statement. You can add the name of
the subprogram after the keyword END for clarity.
D Include at least one RETURN statement in a function.
D Use group functions, such as SUM, in a SQL statement since group functions
apply to groups of rows in a table.
A PL/SQL RECORD can be used to easily create fields that match a database table’s
columns. Each field has the same name and datatype as a column in the table. When
retrieving all columns from a table, use a PL/SQL RECORD to hold the retrieved
values.
Example
Retrieve the order date and the ship date for the specified order. This example raises
an unhandled runtime exception.
PROCEDURE order_info
(id s_ord.id%TYPE)
IS
date_ordered s_ord.date_ordered%TYPE;
date_shipped s_ord.date_shipped%TYPE;
BEGIN
SELECT date_ordered, date_shipped
INTO date_ordered, date_shipped
FROM s_ord
WHERE id = id;
...
END order_info;
PL/SQL> order_info (100);
ERROR 0 at line 1, column 0
Unhandled exception ORA-01422: exact fetch returns
more than requested number of rows
ORA-06512: at line 7
SELECT Exceptions
Condition Exception
The SELECT statement identifies more TOO_MANY_ROWS exception
than one row. (Oracle7 Server error number -1422).
The SELECT statement does not identify NO_DATA_FOUND exception (Oracle7
any rows. Server error number +1403).
Note: Handle the raised exceptions with exception-handling routines, which will be
covered in a later lesson. Alternatively, fetch multiple rows one-by-one in a
loop by declaring an explicit cursor.
TOO_MANY_ROWS Exception
When more than one record is identified with a SELECT statement, Oracle7 Server
raises an error number -1422, also referred to as TOO_MANY_ROWS, which is the
predefined exception name.
NO_DATA_FOUND Exception
When no rows are identified with a SELECT statement, the NO_DATA_FOUND
exception is raised, which is also Oracle7 Server error number +1403.
In the “Processing Queries by Using Explicit Cursors” and “Error Handling” lessons,
options for addressing these exceptions are addressed.
Inserting Data
When adding rows to a table, you can eliminate unnecessary IN arguments.
D Use SQL function, such as USER and SYSDATE.
D Generate primary key values by using database sequences.
D Derive values in the PL/SQL block.
D Add column default values.
Attribute Description
SQL%ROWCOUNT Number of rows affected by the most recent SQL
statement (an integer value).
SQL%FOUND Boolean attribute that evaluates to TRUE if the most
recent SQL statement affects one or more rows.
SQL%NOTFOUND Boolean attribute that evaluates to TRUE if the most
recent SQL statement does not affect any rows.
SQL%ISOPEN Always evaluates to FALSE because PL/SQL closes
implicit cursors immediately after they are executed.
Example
Write a procedure to delete rows that have the specified order number from the item
table. Print the number of rows deleted to the screen.
PROCEDURE del_rows
(v_ord_id NUMBER)
IS
v_rows_deleted NUMBER;
BEGIN
DELETE FROM s_item
WHERE ord_id = v_ord_id;
v_rows_deleted := SQL%ROWCOUNT;
TEXT_IO.PUT_LINE (TO_CHAR(v_rows_deleted)
||’ rows deleted.’);
END del_rows;
COMMIT Command
COMMIT ends the current transaction by making all pending changes to the database
permanent.
Syntax
COMMIT [WORK];
ROLLBACK Command
ROLLBACK ends the current transaction by discarding all pending changes.
Syntax
ROLLBACK [WORK];
SAVEPOINT Command
Alter the transactional logic with Oracle7 Server savepoints based upon runtime
conditions. SAVEPOINT marks an intermediate point in the transaction processing.
Syntax
SAVEPOINT savepoint_name;
Syntax
Statement Description
SELECT Retrieves exactly one row into scalar variables or into a
record variable.
INSERT Adds a row.
UPDATE Modifies one or more existing rows.
DELETE Removes one or more existing rows.
COMMIT Makes all pending transactions permanent.
ROLLBACK Eliminates all pending transactions.
ROLLBACK TO Eliminates all pending transactions since the named
SAVEPOINT savepoint.
You can use SQL implicit cursor attributes to verify the outcome of these statements.
Practice Contents
D Creating a procedure to insert data into a table
D Creating a procedure to update data in a table
D Creating a procedure to delete a record from a table
D Verifying your changes to the table using Oracle Procedure Builder built-ins and
implicit cursor attributes
e. Display the department number, region number, and region name for the
updated department.
3. Create a procedure to delete the department created in Exercise 1.
a. Create a parameter for the department number.
b. Print to the screen the number of rows affected.
c. Test the procedure. What happens if you enter a department number that does
not exist?
You can control the flow of your PL/SQL block by using conditional statements
and loops.
At the end of this lesson, you should be able to
D Conditionally control processing in a PL/SQL block.
D Iterate statements by using various types of loops.
Syntax
IF condition THEN
statements;
[ELSIF condition THEN
statements;]
[ELSE
statements;]
END IF;
Guidelines
D When writing code, remember the spelling of the keywords.
D ELSIF is one word.
D END IF is two words.
D If the controlling Boolean condition is TRUE, the associated sequence of
statements is executed; if the controlling Boolean condition is FALSE or NULL,
the associated sequence of statements is passed over.
D Any number of ELSIF clauses are permitted.
D There can be at most one ELSE clause.
D Indent the conditionally executed statements for clarity.
Simple IF Statements
PL/SQL executes the conditional statements only if the condition is TRUE. If the
condition is FALSE or NULL, then PL/SQL ignores the conditional statements. In
either case, control resumes at the next statement in the program following END IF.
Example
Set the job title to Sales Representative and the region number to 35 if the last name
is Dumas.
. . .
IF v_last_name = ’Dumas’ THEN
v_job := ’Sales Representative’;
v_region_id := 35;
END IF;
. . .
IFĆTHENĆELSE Statements
If the condition is FALSE or NULL, you can use the ELSE clause to carry out other
actions. As with the simple IF statement, control resumes in the program from the
END IF.
Example
Set a flag for orders where there are fewer than five days between order date and ship
date.
. . .
IF v_date_shipped - v_date_ordered < 5 THEN
v_ship_flag := ’Acceptable’;
ELSE
v_ship_flag := ’Unacceptable’;
END IF;
. . .
Nested IF Statements
Either set of actions of the result of the first IF statement can include further IF
statements before specific actions are performed. Each nested IF statement must be
terminated with a corresponding END IF.
IFĆTHENĆELSIF Statements
When possible, however, use the ELSIF clause instead of nesting IF statements. The
code is easier to read and understand. The logic is clearly identified. If the action in
the ELSE clause consists purely of another IF statement, it is more convenient to use
the ELSIF clause. This makes the code clearer by removing the need for nested END
IFs at the end of each further set of conditions and actions.
Example
For a given value entered, return a calculated value. If the entered value is over 100,
then the calculated value is two times the entered value. If the entered value is
between 50 and 100, then the calculated value is 50% of the starting value. If the
entered value is less than 50, then the calculated value is 10% of the starting value.
FUNCTION calc_val
(v_start IN NUMBER)
RETURN NUMBER
IS
BEGIN
IF v_start > 100 THEN
RETURN (2 * v_start);
ELSIF v_start >= 50 THEN
RETURN (.5 * v_start);
ELSE
RETURN (.1 * v_start);
END IF;
END calc_val;
The AND logic table can help you evaluate the possibilities for the Boolean condition
you see below.
. . .
v_flag := v_reorder_flag AND v_available_flag;
. . .
Basic Loop
The simplest loop consists of the body of statements to be repeated enclosed between
the delimiters LOOP and END LOOP. Each time the flow of execution reaches the
END LOOP statement, control is returned to the corresponding LOOP statement
above it. This uncontrolled loop is an infinite loop that is to be avoided. To avoid an
infinite loop, add an EXIT statement.
Syntax
LOOP
statement1;
statement2;
. . .
EXIT [WHEN condition];
END LOOP;
Example
Insert the first ten new line items for order number 101.
. . .
v_ord_id s_item.ord_id%TYPE := 101;
v_counter NUMBER (2) := 1;
BEGIN
. . .
LOOP
INSERT INTO s_item (ord_id, item_id)
VALUES (v_ord_id, v_counter);
v_counter := v_counter + 1;
EXIT WHEN v_counter > 10;
END LOOP;
. . .
FOR Loop
FOR loops have the same general structure as the loops you have already seen. In
addition, they have a control statement at the front of the LOOP keyword to
determine the number of iterations PL/SQL performs.
Syntax
Example
Print the number of times the loop is executed and the last value for the index based
on the supplied lower bound and upper bound.
PROCEDURE iterate
(v_lower NUMBER,
v_upper NUMBER)
IS
v_counter NUMBER(10) := 0;
v_output NUMBER(10);
BEGIN
FOR i IN v_lower..v_upper LOOP
v_counter := v_counter + 1;
v_output := i;
END LOOP;
TEXT_IO.PUT_LINE(’Last value is ’||TO_CHAR(v_output)
||’. Total loops = ’||TO_CHAR(v_counter));
END iterate;
Guidelines
D Reference the index within the loop only; it is undefined outside the loop.
D Reference the existing value of an index within an expression.
D Do not reference the index as the target of an assignment.
WHILE Loop
You can use the WHILE loop to repeat a sequence of statements until the controlling
condition is no longer TRUE. The condition is evaluated at the start of each iteration.
The loop terminates when the condition is FALSE. If the condition is FALSE at the
start of the loop, then no further iterations are performed.
Syntax
...
BEGIN
<<Outer–loop>>LOOP
v_counter :=v_counter+1;
EXIT WHEN v_counter>10;
<<Inner–loop>>LOOP
...
EXIT Outer_loop WHEN total_done = ’YES’;
–– Leave both loops
EXIT WHEN inner_done = ’YES’;
–– Leave inner loop only
...
END LOOP Inner_Loop;
...
END LOOP Outer_loop;
END;
Practice Contents
D Performing conditional actions using the IF statement
D Performing iterative steps by using the loop structure
D Viewing the values variables during runtime by using Procedure Builder
debugging features
2. Write a procedure named CUST_UPDATE that loops through the region numbers
(1 through 5) to update the credit rating of all customers. Do not issue a commit.
a. If the region number is even, then set the credit rating to Excellent (even if the
customer’s credit rating is already Excellent), otherwise set the credit rating to
Good.
b. Once the rows are updated, find out how many rows were updated. Print the
following statements to the screen based on the number of rows updated.
i. If less than three rows updated, statement should read “Fewer than 3
customer records updated for region number X”, where X represents the
region number.
ii. Otherwise, it should read “Y rows updated for region number X”, where Y
is the number of rows updated, and X is the region number.
c. Rollback the changes. Set a breakpoint on the conditional test for the number
of rows updated. Execute the procedure. Check the Stack node to verify the
values of the variables as you Step Into the statements in the loop.
Reminder: You can use the Quick Tour, “Debugging a Program Unit” section
for assistance.
If you have time, complete the following exercise.
3. Create a procedure named EMP_MESSAGE that selects the employee last name,
start date, and salary based on an employee number provided at execution. Print a
message to the screen based on any combination of one of the following criteria.
Test employee numbers 2, 5, 16, 17, and 18. Hint: A nested IF is required.
Criteria Message
Salary greater than 1200 Salary more than 1200
Last name contains “R” Name contains “R”
Start date is in March March start date
None of the above **None**
You may need to use a multiple row SELECT statement within PL/SQL to
process many rows. To accomplish this, you declare and control explicit cursors,
which are used in loops, including the cursor FOR loop.
At the end of this lesson, you should be able to
D Explain the difference between implicit and explicit cursors.
D Declare and use explicit cursors to fetch rows from the database.
D Create an explicit cursor containing parameters.
D Write cursor FOR loops.
Recall that the SELECT statement in PL/SQL must only return a single row. PL/SQL
actually attempts to fetch two rows from an implicit cursor: one to satisfy the query,
and a second to see if further rows were returned. One method to eliminate this extra
fetch is to use an explicit cursor.
Syntax
DECLARE
CURSOR cursor_name IS
select_statement;
Syntax
OPEN cursor_name;
Syntax
Guidelines
D Include the same number of variables within the INTO clause of the FETCH
statement as output columns in the SELECT statement, and be sure that the
datatypes are compatible.
D Match each variable to correspond to the columns positionally.
D Alternatively, define a record for the cursor and reference the record in the
FETCH INTO clause.
D Test to see if the cursor contains rows. If a fetch acquires no values, that is, there
are now rows left to process in the active set and no error is recorded.
Syntax
CLOSE cursor_name;
Note: Do not attempt to fetch data from a cursor once it has been closed or the
INVALID_CURSOR exception will be raised.
You can only fetch rows when the cursor is open. Determine whether the cursor is
open using the %ISOPEN cursor attribute, if necessary.
Fetch rows in a loop. Determine when to exit the loop by using cursor attributes.
To retrieve an exact number of rows, fetch the rows in a numeric FOR loop, or fetch
the rows in a simple loop and determine when to exit the loop by using the
%ROWCOUNT cursor attribute.
Example
Retrieve the first five line items for an order one by one. Print the cumulative total for
each product to the screen.
PROCEDURE ord_process
(v_ord_id IN s_item.ord_id%TYPE)
IS
v_product_id s_item.product_id%TYPE;
v_item_total NUMBER (11,2);
v_order_total NUMBER (11,2) := 0;
CURSOR item_cursor IS
SELECT product_id, price * quantity
FROM s_item
WHERE ord_id = v_ord_id;
BEGIN
OPEN item_cursor;
LOOP
FETCH item_cursor INTO v_product_id, v_item_total;
EXIT WHEN item_cursor%ROWCOUNT > 5
OR item_cursor%NOTFOUND;
v_order_total := v_order_total + v_item_total;
TEXT_IO.PUT_LINE (’Product ID ’||
TO_CHAR(v_product_id)||
’ has a total of ’||
TO_CHAR(v_order_total,’$999,999,999.99’));
END LOOP;
CLOSE item_cursor;
END ord_process;
Note: If using %ROWCOUNT, add a test for no rows in the cursor by using the
%NOTFOUND attribute because the rowcount is not incremented if the fetch
does not retrieve any rows.
Syntax
Syntax
Guidelines
D Do not declare the record that controls the loop. Its scope is only in the loop.
D Test the cursor attributes during the loop, if required.
D Supply the parameters for a cursor, if required, in parentheses following the
cursor name in the FOR statement.
D Do not use a cursor FOR loop when the cursor operations have to be handled
manually.
Syntax
When querying multiple tables, you can use the FOR UPDATE clause to confine row
locking to particular tables. Rows in a table are locked only if the FOR UPDATE
clause refers to a column in that table.
Cursor Types
D Implicit cursors are used for all DML statements and single row queries.
D Explicit cursors are used for queries of zero, one, or more rows.
Cursor Attributes
Evaluate the status of the cursor by using cursor attributes.
Practice Contents
D Declaring and using a cursor to query rows of a table
D Using a cursor FOR loop
D Applying cursor attributes to test the cursor status
1. Create a procedure named TOP_DOGS1 that determines the top employees with
respect to salaries.
a. Prepare for this exercise by creating a new table for storing employees and
their salaries.
b. Add a parameter to accept the user input n for the top number of employees.
c. Write a cursor FOR loop to get the last names and salaries of the top n people,
with respect to salary, from the S_EMP table.
d. Store the names and salaries in the TOP_DOGS table.
e. Assume for the moment that no two employees have the same salary.
f. Test the exercise under a variety of special cases, such as n = 0, n is greater
than the number of employees in the S_EMP table.
g. Empty the TOP_DOGS table after each test.
2. Create a stored procedure named ADD_STARS to reward all employees by
appending an asterisk in the STARS column for every commission point.
a. Prepare for this exercise by creating a new column in the S_EMP table for
storing asterisks (*).
Error Handling
25Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives
When you execute PL/SQL code, you may encounter errors. Errors cause the
PL/SQL block to halt with an exception. You can trap the exception and
perform actions conditionally using exception handlers.
At the end of this lesson, you should be able to
D Identify common exceptions.
D Describe the three basic types of exceptions.
D Write exception handling routines.
Trapping an Exception
If the exception is raised in the executable section of the block, processing branches
to the corresponding exception handler in the exception section of the block. If
PL/SQL successfully handles the exception, then the exception does not propagate to
the enclosing block or environment.
Propagating an Exception
The other method for handling an exception is to allow it to propagate to the calling
environment. If the exception is raised in the executable section of the block and
there is no corresponding exception handler, the PL/SQL block terminates with
failure.
Syntax
EXCEPTION
WHEN exception1 [OR exception2 . . .] THEN
statement1;
statement2;
. . .
[WHEN exception3 [OR exception4 . . . THEN
statement1;
statement2;
. . .]
[WHEN OTHERS THEN
statement1;
statement2;
. . .]
Guidelines
D Place the WHEN OTHERS clause after all other exception handling clauses.
D You can have at most one WHEN OTHERS clause.
D Begin exception-handling section of the block with the keyword EXCEPTION.
D Define several exception handlers, each with their own set of actions, for the
block.
D When an exception occurs, PL/SQL will process only one handler before leaving
the block.
For more information, see
Oracle Course Catalog to attend Develop Applications with Database Procedures
course.
Oracle Server
Exception Name Error Number Description
NO_DATA_FOUND ORA-01403 Single row SELECT returned no data.
TOO_MANY_ROWS ORA-01422 Single row SELECT returned more
than one row.
INVALID_CURSOR ORA-01001 Illegal cursor operation occurred.
ZERO_DIVIDE ORA-01476 Attempted to divide by zero.
DUP_VAL_ON_INDEX ORA-00001 Attempted to insert a duplicate value
into a column that has a unique index.
You can use the debugging capabilities in Procedure Builder to identify and trap
exceptions prior to moving procedures to the database.
Example
Eliminate all inventory items for a particular product. Be sure the product number is
valid.
PROCEDURE elim_inventory
(v_product_id IN s_product.id%TYPE) IS
v_id s_product.id%TYPE;
BEGIN
SELECT id
INTO v_id
FROM s_product
WHERE id = v_product_id;
DELETE FROM s_inventory
WHERE product_id = v_product_id;
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
ROLLBACK;
TEXT_IO.PUT_LINE(TO_CHAR(v_product_id)||
’ is invalid.’);
WHEN TOO_MANY_ROWS THEN
ROLLBACK;
TEXT_IO.PUT_LINE(’Data corruption in S_PRODUCT.’);
WHEN OTHERS THEN
ROLLBACK;
TEXT_IO.PUT_LINE(’Other error occurred.’);
END elim_inventory;
Syntax
exception EXCEPTION;
2. Associate the declared exception with the standard Oracle7 Server error number
using the pragma EXCEPTION_INIT statement.
Syntax
2 2
3 3
Syntax
exception EXCEPTION;
2. Raise the exception explicitly within the executable section using the RAISE
statement.
Syntax
RAISE exception;
When an exception is trapped in the WHEN OTHERS section, you can use a set of
generic functions for identifying those errors.
Function Description
SQLCODE Returns the numeric value for the error code. You can assign it
to a NUMBER variable.
SQLERRM Returns character data containing the message associated with
the error number.
Exception Types
D Predefined Oracle7 Server error.
D Non-predefined Oracle7 Server error.
D User-defined error.
Handle Exceptions
D Trap the exception within the PL/SQL block in an exception handling routine.
D Allow the exception to propagate to the calling environment.
Propagate Exceptions
D Propagate an exception through a series of nested blocks.
D Terminate PL/SQL processing with success by handling the exception in an
enclosing block.
D Terminate the PL/SQL processing with failure by passing the unhandled
exception to the calling environment.
Practice Contents
D Handling named exceptions
D Creating and invoking user-defined exceptions
c. Write an exception handler for the error to pass a message to the user that the
specified region does not exist.
d. Execute the procedure by entering the following text.
e. Write an exception handler for the error to pass a message to the user that the
specified region already has a department of that name.
f. Execute the procedure by entering the following text.
g. Write an exception handler for the error to pass a message to the user that the
specified department number does not exist.
Your results should look like the list below. Results have been formatted to fit
the page.
Summary of PL/SQL
26Ć2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary
PL/SQL (Procedural Language/SQL) is an extension to SQL. It is a language that
allows you to combine multiple SQL statements with procedural controls such as
identifiers, conditional, and iterative constructs in a PL/SQL block.
Benefits from PL/SQL
D Modularize program development by grouping similar concepts together and
nesting blocks
D Declare identifiers, for example, variables, constants, and cursors
D Program with procedural language structures, for example, IF statements and
loops
D Exception handling for Oracle7 Server errors and user-defined exceptions
D Port code between applications and the Oracle7 Server
D Integrate Oracle7 stored subprograms and application subprograms
D Improve performance by sending a block of code to the server
PL/SQL Block
A PL/SQL block contains code in up to four sections. The header section is where
you set the name and parameters for named blocks. The declarative section is
optional and contains all variables, constants, cursors, and user-defined exceptions
that will be referenced within the executable section. The executable section is
required and contains SQL statements to manipulate data in the database and PL/SQL
statements to manipulate data in the block. The exception-handling section is optional
and specifies the actions to perform when errors and abnormal conditions arise within
the executable section.
Anonymous Blocks
Anonymous blocks are unnamed blocks. They are declared at the point in an
application where they are to be executed and are passed to the PL/SQL engine for
execution at runtime. You can embed an anonymous block within a precompiler
program and within SQL*Plus or Server Manager. Triggers in Developer/2000
components consist of such blocks.
Procedures
Procedures are named PL/SQL blocks that store a series of actions for later execution.
The procedure can contain zero or more parameters, which are arguments that you list
when calling the procedure. Procedures can either be application specific or stored in
the Oracle7 Server.
Functions
A function returns a value to the calling environment. You must declare the RETURN
datatype in the header section of the function definition, and define the value to be
returned in the PL/SQL block. You can also declare a list of parameters to be passed
into the function. Functions are called as part of an expression.
DML in PL/SQL
You can use DML statements in your PL/SQL blocks. Use the SELECT statement to
retrieve data from the database.
D The SELECT statement contains an additional mandatory clause: the INTO
clause. In the INTO clause, list the output variables for receiving the data. The
SELECT statement must return exactly one row or an error will occur.
D The INSERT statement adds new rows of data to the table.
D The UPDATE statement modifies existing rows in the table.
D The DELETE statement removes unwanted rows from the table.
D COMMIT ends the current transaction by making all pending changes to the
database permanent.
D ROLLBACK ends the current transaction by discarding all pending changes.
IF Conditional Statements
The PL/SQL IF statement is similar to the structure of IF statements in other
procedural languages. It allows PL/SQL to perform actions selectively based upon
conditions. If the controlling Boolean condition is TRUE, the associated sequence of
statements is executed; if the controlling Boolean condition is FALSE or NULL, the
associated sequence of statements is passed over.
Cursors
PL/SQL cursors let you name a private SQL area and access its stored information.
The cursor directs all phases of processing. Explicit cursors are declared and named
by the programmer and manipulated through specific statements within the block’s
executable actions. Control explicit cursors in a loop with four steps: declare, open,
fetch, and close. Cursor FOR loops are a shortcut to open the cursor, fetch rows once
for each loop iteration, and automatically close the cursor after all rows are
processed.
Exception Handling
An exception is an identifier in PL/SQL, raised during the execution of a block that
terminates its main body of actions. A block will always terminate when PL/SQL
raises an exception, but you specify an exception handler to perform final actions.
Exceptions can be raised either by the Oracle7 Server or by the user. You can either
trap an exception in the exception-handling section of the block, or allow it to
propagate to the calling environment.
Procedure Builder
Oracle Procedure Builder is a tool you can use to create, execute, and debug PL/SQL
programs used in your application tools, such as a form or report, or on the Oracle7
Server through its graphical interface.
Practice Contents
D Creating procedures and functions
D Inserting, updating, and deleting data
D Incorporating IF statements and loops
D Handling exceptions
Note: If you are new to the class, you can execute the buildvid.sql script in
SQL*Plus to create and populate the tables. If you want to drop the work you
did in the course summary from the SQL section, you can execute the
dropvid.sql script in SQL*Plus to drop their tables. Then, you can execute the
buildvid.sql script in SQL*Plus to create and populate the tables.