Beruflich Dokumente
Kultur Dokumente
Version: ORACLE/HANDOUT/0704/1.0
Date: 27-07-04
TABLE OF CONTENTS
Introduction ........................................................................................................................6
About this Module ...............................................................................................................6
Target Audience .................................................................................................................6
Variables .......................................................................................................................... 25
Data Types ....................................................................................................................... 25
Composite Types .............................................................................................................. 25
Fetch Cursor..................................................................................................................... 33
Close Cursor .................................................................................................................... 34
Understanding Exceptions ................................................................................................. 38
Predefined Exceptions....................................................................................................... 38
User Defined Exception ..................................................................................................... 39
PRAGMA EXCEPTION_INIT ............................................................................................. 40
RAISE_APPLICATION_ERROR ........................................................................................ 40
SUMMARY ....................................................................................................................... 40
Test your Understanding ................................................................................................... 41
Chapter 5: Triggers............................................................................................................. 47
Learning Objectives .......................................................................................................... 47
Appreciate Database Triggers............................................................................................ 47
Types of Collection............................................................................................................ 51
Define and Declare Collection ............................................................................................ 52
Use Collection Methods ..................................................................................................... 53
SUMMARY ....................................................................................................................... 60
WEBSITES....................................................................................................................... 61
BOOKS ............................................................................................................................ 61
STUDENT NOTES: .............................................................................................................. 62
Introduction
About this Module
The module tells the student about the basics of PL/SQL statements in Oracle.
Target Audience
Entry Level Trainees
Module Objectives
Pre-requisite
The student needs to have an idea of the following:
?? General Programming and Logic
?? Structured Query Language
?? Relational DBMS
Learning Objectives
Learn SQL*Plus
Logging in:
?? Ensure that Oracle is installed in your computer
Entering Commands
To tell SQL Plus what to do, simply enter the command you wish to use. Commands can either
be in Lower or Upper case, for the sake of clarity, all table names, column names, and
commands in this Guide appear in capital letters.
?? SQL*Plus commands, for formatting query results, setting options, and editing
and storing SQL commands and PL/SQL blocks
Getting Help
Type HELP at the command prompt followed by the name of the command to get online help for
SQL*Plus commands. For example:
SQL>HELP ACCEPT
Executing Commands
After you enter the command and direct SQL*Plus to execute it, SQL*Plus processes
the command and re-displays the command prompt, indicating that you can enter
another command.
2. SQL*Plus will display a "2", the prompt for the second line. Enter the second
line of the command:
The above command shall display the salaries below Rs. 2500 for all employees
SQL> SELECT EMPNO, ENAME, JOB, SAL FROM EMP WHERE SAL < 2500;
SQL> SELECT
2 EMPNO, ENAME, JOB, SAL
3 FROM EMP
4 WHERE SAL < 2500;
CREATE FUNCTION
CREATE LIBRARY
CREATE PACKAGE
CREATE PACKAGE BODY
CREATE PROCEDURE
CREATE TRIGGER
CREATE TYPE
An SQL command is entered at the SQL prompt and the subsequent lines are numbered. This is
called SQL buffer
SELECT ename, job, sal INTO my_ename, my_job, my_sal FROM emp
WHERE empno = my_empno;
In the following example, the SQL engine loads the entire empno and ename
database columns into nested tables before returning the tables to the PL/SQL:
DECLARE
TYPE NumTab IS TABLE OF emp.empno%TYPE;
TYPE NameTab IS TABLE OF emp.ename%TYPE;
enums NumTab; -- no need to initialize
names NameTab;
BEGIN
SELECT empno, ename BULK COLLECT INTO enums, names FROM emp;
...
END;
Syntax:
SELECT <COLUMN NAME (S)/*
FROM EMP
WHERE <CONDITION>
The following four elements can be used with the WHERE clause:
?? Column name
?? Comparison Operators
?? Constants
?? List of values
Example:
SELECT EMPNO, ENAME, SAL
FROM EMP
WHERE SAL > 2500;
Use Operators
What is an Operator?
An operator manipulates individual data items and returns a result. The data items
are called operands or arguments. Operators are represented by special characters or
by keywords. For example, an asterisk represents the multiplication operator
(*) and the operator that tests for nulls is represented by the keywords IS NULL.
Unary:
A unary operator operates on only one operand. A unary operator typically appears with its
operand in this format:
operator operand
Binary:
A binary operator operates on two operands. A binary operator appears with its operands in this
format:
Arithmetic Operators
You can use an arithmetic operator in an expression to negate, add, subtract, multiply, and divide
numeric values. The result of the operation is also a numeric value. Some of these operators are
also used in date arithmetic. An example of arithmetic operators is given in the following:
Concatenation Operator
The concatenation operator manipulates character strings. The following example shows the use
of Concatenation operators:
This selects character strings with ‘Name is’ from the database emp.
Comparison Operators
Comparison operators compare one expression with another. The result of such a comparison
can be TRUE, FALSE, or UNKNOWN. Example of a Comparison Operator is given below:
The Comparison operator above shall select all salaries that are higher than 1500 in the emp
database.
Logical Operators
A logical operator combines the results of two component conditions to produce a
single result based on them or to invert the result of a single condition. An example of a logical
operator is given below:
SELECT *
FROM emp
WHERE job = ’CLERK’
AND deptno = 10;
Set Operators
Set operators combine the results of two component queries into a single result.
Queries containing set operators are called compound queries.
Sort Rows
The ORDER BY Clause
ORDER BY clause is used to arrange the output
Default order is ascending (ASC)
For arranging in descending order, DESC is used
ORDER BY should be the last clause in a SELECT statement
Can be arranged in multiple columns
Example
Example
select ename, job, hiredate
from emp
order by hiredate desc;
Null values are displayed last for ascending sequences, and are reported first when rows are
sorted in descending order.
Example
select ename, job, deptno
from emp
order by deptno, sal desc;
Understand Functions
Functions are similar to operators in that they manipulate data items and return a result.
Functions differ from operators in the format of their arguments. This format allows them to
operate on zero, one, two, or more arguments. Basically, there are two kinds of Functions:
SQL functions
SQL functions are built into Oracle and are available for use in various appropriate
SQL statements.
?? Number
?? Date
?? Conversion
?? List
?? General Functions
?? WHERE
?? ORDER BY
Example:
SELECT LOWER (‘ORACLE’) FROM DUAL;
Single row functions and data type conversions are an area where the SQL used be different
DBMS vendors varies greatly.
Thus, the operations described here will work only for ORACLE databases.
?? AVG
?? MAX
?? MIN
?? COUNT (*)
?? COUNT (column name)
GROUP BY Clause
?? Query results can be summarized using the GROUP BY clause.
?? Multiple columns can be used in GROUP BY clause.
Example
SELECT DEPTNO, SUM (SAL)
FROM EMP
GROUP BY DEPTNO;
Sequence:
?? Rows are first grouped
Example:
SELECT DEPTNO, SUM (SAL)
FROM EMP
GROUP BY DEPTNO
HAVING SUM (SAL) > 10000;
Understand Joins
A join is a query that combines rows from two or more tables, views, or materialized views
("snapshots"). Oracle performs a join whenever multiple tables appear in the query’s FROM
clause. The query’s select list can select any columns from any of these tables. If any two of
these tables have a column name in common, you must qualify all references to these columns
throughout the query with table names to avoid ambiguity.
Understand Equi-Joins
What is an Equi-join?
?? Is defined as a join in which more than one tables are joined together with the help of
a common column that exists in both the tables
?? In this type of join the relationship between the tables are specified in the where
clause, by using an equal (=) symbol
?? EQUI Joins are also called simple joins and inner joins
Example
SELECT EMPNO, ENAME, DNAME
FROM EMP, DEPT
WHERE DEPT.DEPTNO = EMP.DEPTNO
Removing Ambiguity
?? When more than one column joined, and if one column exists in both the tables and
that column needs to be displayed in the output, it must be preceded by the table
name followed by a period (.)
?? Otherwise an ambiguity will occur because SQL will not understand from which table
the said column to display
Example
SELECT DEPT.DEPTNO, EMPNO FROM EMP, DEPT WHERE
EMP.DEPTNO=DEPT.DEPTNO
Table Aliases
?? Should not be more than 30 characters long, but the shorter it is the better.
?? The table alias should be substituted for the table name throughout the SELECT
statement.
?? Valid only for the current SELECT statement.
?? Should be meaningful.
Example:
SELECT E.DEPTNO, ENAME, DNAME
Understand Outer-Joins
An outer join extends the result of a simple join. An outer join returns all rows that satisfy the join
condition and those rows from one table for which no rows from the other satisfy the join
condition. A simple join does not return such rows. To write a query that performs an outer join of
tables A and B and returns all rows from A, apply the outer join operator (+) to all columns of B in
the join condition. For all rows in A that have no matching rows in B, Oracle returns NULL for any
select list expressions containing columns of B.
Outer join queries are subject to the following rules and restrictions:
?? The (+) operator can appear only in the WHERE clause or, in the context of left
correlation (that is, when specifying the TABLE clause) in the FROM clause, and can
be applied only to a column of a table or view.
?? If A and B are joined by multiple join conditions, you must use the (+) operator in all
of these conditions. If you do not, Oracle will return only the rows resulting from a
simple join, but without a warning or error to advise you that you do not have the
results of an outer join.
?? The (+) operator can be applied only to a column, not to an arbitrary expression.
However, an arbitrary expression can contain a column marked with the (+) operator.
Example:
SELECT E.ENAME, E.SAL, F.ENAME, F.SAL
FROM EMP E, EMP F
WHERE E.SAL = F.SAL AND E.EMPNO < F.EMPNO;
?? Multiple row sub query (Multi row comparison operator e.g. IN,SOME/ANY or ALL
operators)
Example
SELECT EMPNO, ENAME, SAL
FROM EMP
WHERE SAL=(SELECT MAX (SAL) FROM EMP);
EXISTS Operator
?? Exists returns a value TRUE if the sub-query that follows it returns at least one row
Example
SELECT EMPNO, ENAME, DEPTNO FROM EMP WHERE EXISTS
(SELECT COUNT (*) FROM EMP WHERE DEPTNO=30
HAVING COUNT (*) > 5)
ORDER BY DEPTNO;
ANY Operator
?? Compares with any of the values returned by the inner query
Example
SELECT EMPNO, ENAME, SAL FROM EMP
WHERE SAL > ANY
(SELECT SAL FROM EMP WHERE DEPTNO = 10);
ALL Operators
?? Compares with all the values returned by the inner query
Example
SELECT EMPNO, ENAME, SAL FROM EMP
WHERE SAL > ALL
(SELECT SAL FROM EMP WHERE DEPTNO = 10);
?? Each execution of the outer query will ensure the inner query to be executed for all of
its values
Example
Select ename, deptno
from dept
where 4> (select COUNT(*)
from emp
where dept.deptno= emp.deptno);
Create Tables
Rules for naming a table
?? The name must begin with a letter, A-Z or a-z.
?? May contain letters, numeric and special character _(underscore). The $ and # are
also legal but discouraged;
?? The name is the same whether upper or lower case letters are used
?? It may be up to 30 char length
?? The name must not duplicate the name of any other object in your account.
?? The name must not be a sequel reserved word
Example
INSERT
Use INSERT INTO to insert a new row in table
UPDATE
Use UPDATE to update a single row/multiple rows in table
DELETE
Use DELETE to delete a single row/multiple rows from table
An automatic ROLLBACK occurs under an abnormal termination of SQL *PLUS or due to system
failure
SUMMARY
?? SQL is an English-like, non-procedural language
?? SQL is used in creating, modifying and deleting database objects
?? SQL is used in inserting, updating and deleting rows in a table
?? SQL is used in controlling access to the database and database objects
?? SQL *PLUS is an Oracle tool. It recognizes and submits SQL statements residing in
the SQL buffer (memory area) for execution to the Oracle server
?? SQL *PLUS has its own sets of commands
?? SELECT Statement is used to retrieve data from the database either selectively or
collectively
?? The WHERE clause is used to apply conditions to filter rows
?? SQL provides a set of built-in functions, namely Single Row Functions and Aggregate
functions
?? Data from multiple tables can be queried using SQL Join. They are of three types,
Equi Join, Outer Join and Self Join
?? Sub-queries is a select statement that is nested within another select statement
?? Oracle provides DDL statements for Creating, Altering, Dropping and Truncating
Tables
?? Oracle provides DML statements to insert, update and delete rows
?? COMMIT makes permanent any database changes you made during the current
transaction. Until you commit your changes, other users cannot see them.
?? ROLLBACK ends the current transaction and undoes any changes made since the
transaction began
PL/SQL Features
Variables
?? Variables are memory locations, which can store data values
?? Information from database can be assigned to a variable, or the contents of a
variable can be inserted into the database
?? The variables are declared in the declarative section of the block
?? Every variable has a specific type which describes what kind of information it can
store
Variable Declarations
Declaration Syntax
variable_name type [CONSTANT][NOT NULL][:=value]
Example
DECLARE
v_Description VARCHAR2(50);
v_NumberSeats NUMBER := 45;
v_Counter BINARY_INTEGER DEFAULT 0;
Data Types
?? BINARY_INTEGER
?? DEC
?? DECIMAL
?? DOUBLE PRECISION
?? FLOAT
?? INT
?? INTEGER
?? NATURAL
?? NUMBER
?? NUMERIC
?? POSITIVE
?? REAL
?? SMALLINT
Composite Types
PL/SQL Record
?? A record is similar to “C” structure
?? Record provide a way to deal with separate but related variables as Unit
?? To use, developer must define the type, then declare variables of that type
?? To refer to a field within a record , dot notation is used
Example
DECLARE
REC1 EMP%ROWTYPE;
REC2 EMP%ROWTYPE
PL/SQL Statements
Statements in PL/SQL
?? The INTO clause must be used to store a table column value into a variable declared
in the DECLARATION section of PL/SQL block
SELECT ENAME INTO MEMNAME FROM EMP WHERE EMPNO=101176;
?? Multiple column values can be assigned to equal number of memory variables using
single INTO
SELECT ENAME, SAL INTO MEMNAME, MEMSAL FROM EMP WHERE
EMPNO=101176;
Packages have many advantages over stand-alone procedures and functions, for instance, they:
Package Description
Calendar Provides calendar maintenance functions
Provides support for the asynchronous notification of database
DBMS_ALERT events.
DBMS_AQ Lets you add a message (of a predefined object type) onto a
queue or to dequeue a message
Lets you perform administrative functions on a queue or queue
DBMS_AQADM table for messages of a predefined object type.
Operator:
An operator is used to manipulate individual data items and return a result. These items are
called operands or arguments. Operators are represented by special characters or by keywords.
For example, the multiplication operator is represented by an asterisk (*) and the operator that
tests for nulls is represented by the keywords IS NULL. The main SQL operators are described
below:
Unary and Binary Operators:
A unary operator operates on only one operand. A unary operator typically appears with its
operand in this format: operator operand
A binary operator operates on two operands. A binary operator appears with its operands in this
format: operand1 operator operand2
Precedence:
An important property of an operator is its precedence. Precedence is the order in which Oracle
evaluates different operators in the same expression. When evaluating an expression containing
multiple operators, Oracle evaluates operators with higher precedence before evaluating those
with lower precedence. Oracle evaluates operators with equal precedence from left to right within
an expression.
Arithmetic Operators:
You can use an arithmetic operator in an expression to negate, add, subtract, multiply, and divide
numeric values. The result of the operation is also a numeric value. Some of these operators are
also used in date arithmetic. Some examples of arithmetic operators are:
+, -, *, / etc.
Character Operators:
Character operators are used in expressions to manipulate character strings. Following is an
example of a character operator:
Comparison Operators:
Comparison operators are used in conditions that compare one expression to another. The result
of comparing one expression to another can be TRUE, FALSE, or UNKNOWN. Below is given
an example of a comparison Operator:
Logical Operators:
A logical operator combines the results of two component conditions to produce a single result
based on them or to invert the result of a single condition. The main comparison operators are:
AND, Not and OR Below is given an example of a comparison Operator:
Operator Function Example
NOT Returns TRUE if the following condition is FALSE. Returns SELECT *
Set Operators:
Set operators combine the results of two component queries into a single result. Queries
containing set operators are called compound queries. The main set operators are: UNION,
UNION ALL, INTERSECT and MINUS
Expression:
An expression is a sequence of variables and literals, separated by operators. The most basic
operator is assignment.
Syntax
Variable: = expression
Variable is PL/SQL variable and expression is PL/SQL expression
IF is_number (current_char)
OR is_letter (current_char)
THEN
new_char: = current_char;
ELSIF current_char = ' '
THEN
new_char: = '+';
ELSE
new_char := convert_to_hex (current_char);
END IF;
Loops:
Looping, or iteration, causes the block between the keywords LOOP and END LOOP to be
repeatedly executed. The loop ends, or terminates, when an exit condition is met. Once a loop
terminates, program control is returned to the first line after the END LOOP keyword. There are
three looping structures: simple, WHILE, and FOR.
In the simple loop, the exit condition is embedded inside the loop body. The EXIT command
terminates the loop immediately, and is usually embedded inside an IF...THEN statement. EXIT
WHEN combines EXIT with a conditional to form a more compact syntax. Here are two
constructions of a simple loop. The first example uses EXIT:
LOOP
COUNT: = COUNT + 1;
IF COUNT > 10
THEN
EXIT;
END IF;
END LOOP;
In the second kind of loop, the WHILE loop, the exit condition is outside the body of the loop. The
code within the body of the loop iterates while the loop condition is true. The loop terminates
when the condition is false, for example:
WHILE (COUNT <= 10)
©Copyright 2004, Cognizant Academy, All Rights Reserved 30
Oracle
LOOP
COUNT: = COUNT + 1;
END LOOP;
The last kind of loop, the FOR loop, iterates a predetermined number of times. For example, the
number of loops needed to process each month in the year does not depend on a complex
condition; it always requires 12 passes through the loop. A FOR loop is controlled by an index
variable that ranges from a lower bound to an upper bound. The index variable begins at the
lower bound. Each pass through the loop increments it. The loop terminates when the index
reaches the upper bound, for example:
FOR month_index IN 1.. 12
LOOP
process_month_sales (month_index);
END LOOP;
SUMMARY
?? PL/SQL extends SQL by adding constructs found in other procedural languages like
conditional constructs, looping, variables data types, procedures, functions etc.
?? Data types can be Scalar types and Composite types.
?? Composite Types can be PL/SQL Record and PL/SQL Tables
?? A Record is like a ‘C’ structure. The %ROWTYPE attribute is used to declare a
record based upon a collection of database columns from a table or view
?? A table is like a ‘C’ array. A Table can have only one primary key
(BINARY_INTEGER) and a column
??
Test your Understanding
Write a PL/SQL block to print the Department wise Employee Details, with Total for each
department as well as Grand Total. The report should look like this,
Learning Objectives
Understand Cursors
A cursor is a mechanism by which you can assign a name to a "select statement" and
manipulate the information within that SQL statement. In other words, A cursor is a SELECT
statement that is defined within the declaration section of your PLSQL code. We'll take a look at
three different syntaxes for cursors. There are two types of cursors: Implicit and Explicit. An
Implicit cursor is used for all other SQL statements. Implicit Cursors gives less programmatic
control. In explicit cursor the cursor name is explicitly attached to a select statement
The four PL/SQL steps necessary for explicit cursor processing are as follows:
?? Declare the cursor
?? Open the cursor
?? Fetch the results into PL/SQL variables
?? Close the cursor
?? To use a cursor, it must be declared first
Syntax
CURSOR cursor_name IS SELECT_statement;
Open Cursors:
Once you've declared your cursor, the next step is to open the cursor
The basic syntax to OPEN the cursor is:
OPEN cursor_name;
For example, you could open a cursor called c1 with the following command:
OPEN c1;
BEGIN
open c1;
fetch c1 into cnumber;
if c1%notfound then
cnumber := 9999;
end if;
close c1;
RETURN cnumber;
END;
Fetch Cursor
The purpose of using a cursor, in most cases, is to retrieve the rows from your cursor so that
some type of operation can be performed on the data. After declaring and opening your cursor,
the next step is to FETCH the rows from your cursor.
CURSOR c1
IS
SELECT course_number
from courses_tbl
where course_name = name_in;
The command that would be used to fetch the data from this cursor is:
FETCH c1 into cnumber;
This would fetch the first course_number into the variable called cnumber;
The final step of working with cursors is to close the cursor once you have finished using it.
The basic syntax to CLOSE the cursor is:
CLOSE cursor_name;
For example, you could close a cursor called c1 with the following command:
CLOSE c1;
BEGIN
open c1;
fetch c1 into cnumber;
if c1%notfound then
cnumber := 9999;
end if;
close c1;
RETURN cnumber;
END;
Cursor Attributes:
While dealing with cursors, you may need to determine the status of your cursor. The
following is a list of the cursor attributes that you can use:
Attributes Explanation
%ISOPEN Returns TRUE if the cursor is open, FALSE if the cursor is closed
Returns INVALID_CURSOR if cursor is declared, but not open; or if
cursor has been closed.
Returns NULL if cursor is open, but fetch has not been executed.
%FOUND
Returns TRUE if a successful fetch has been executed.
Returns FALSE if no row was returned.
Return NULL if cursor is open, but fetch has not been executed.
Returns FALSE if a successful fetch has been executed.
Returns TRUE if no row was returned.
BEGIN
open c1;
fetch c1 into cnumber;
if c1%notfound then
cnumber := 9999;
end if;
close c1;
RETURN cnumber;
END;
Cursor Examples:
The Following example shows a procedure that outputs a dynamic PLSQL cursor. The
example states a problem and shows how to solve it.
Question: In Oracle, I have a table called "wine" and a stored procedure that outputs a cursor
based on the "wine" table.
I've created an HTML Form where the user can enter any combination of three values to retrieve
results from the "wine" table. My problem is that I need a general "select" statement that will work
no matter what value(s), the user enters.
Example:
parameter_1= "Chianti"
parameter_2= "10"
parameter_3= wasn't entered by the user but I have to use in the select statement. And
this is my problem. How to initialize this parameter to get all rows for column3?
Answer: To solve your problem, you will need to output a dynamic PLSQL cursor in Oracle.
Let's take a look at how we can do this. We've divided this process into 3 steps.
END find_wine2;
Understanding Exceptions
What is an Exception?
Exceptions are errors raised whenever there is any in a particular PL/SQL block. This causes a
termination in the program by Oracle. Control then is transferred to the separate exception
section of the program, if one exists, to handle the exception.
Types of Exceptions:
?? Predefined Exception
?? User Defined Exception
Predefined Exceptions
Oracle has a list of Predefined exceptions. They are generated mostly with the SELECT
statement. They are generated implicitly at runtime. Following is a list of the predefined
exceptions that Oracle recognises:
PRAGMA EXCEPTION_INIT
The pragma EXCEPTION_INIT associates an exception name with an Oracle error number. That
lets you refer to any internal exception by name and to write a specific handler for it instead of
using the OTHERS handler.
Syntax
PRAGMA EXCEPTION_INIT (EXCEPTION, ERROR_NUMBER);
Example
DECLARE
MYEXP EXCEPTION;
PRAGMA EXCEPTION_INIT (MYEXP, -1422);
RAISE_APPLICATION_ERROR
What is RAISE_APPLICATION_ERROR?
The RAISE_APPLICATION_ERROR is a procedure that communicates application-specific
errors from the server side (usually a database trigger) to the client-side application. This built-in
procedure is the only mechanism available for communicating a server-side, programmer-defined
exception to the client side in such a way that the client process can handle the exception. Error
number should be of the range between –20000 and –20999. Error messages should be less
than 512 characters.
Syntax
RAISE_APPLICATION_ERROR (error_number in NUMBER, error_msg in VARCHAR2);
Example
IF age < 18 THEN
RAISE_APPLICATION_ERROR (-20001, ‘Must be eighteen years of age.');
END IF;
SUMMARY
?? Explicit cursor handling requires Declaring, Opening, Fetching and Closing cursor
?? Oracle raises ERRORS whenever any abnormal situation arises in a PL/SQL block
and performs an illegal termination of the execution of the program
?? PL/SQL traps and responds to errors using an architecture of EXCEPTION handler
?? Pre-defined exceptions are already defined in the STANDARD package
?? Exceptions can be pre-defined(built-in) and user-defined
1. Create a cursor to print empno, ename, job, sal, hiredate and the increment amount for
all employees. Increment amount depends on the day of joining
Day of Joining Increment in %
Friday 20
Wednesday 18
Thursday 17
For all others 15
Learning Objectives
On completion of this Chapter, you will be able to:
?? Understand & Write Procedures
Understand Procedures
What is a Procedure?
It is a sub program in the PL/SQL block, which can perform a specific task when invoked explicitly
with or without parameter. A Procedure has two parts: Specification and Body
Specification: This section begins with the keyword Procedure followed by its name and
Parameter list (optional)
Body: Procedure Body begins with the keyword IS/AS and ends with the keyword END followed
by the procedure name (optional)
Syntax
CREATE OR REPLACE PROCEDURE <PROCEDURE_NAME>
(<PARAMETER> [MODE] <DATA TYPE>,)
IS/AS
[LOCAL VARIABLE DECLARATION]
BEGIN
PL/SQL EXECUTABLE STATEMENT
[EXCEPTION]
[EXCEPTION HANDLERS]
END [PROGRAM UNIT NAME];
Creating Procedures
In Oracle, you can create your own procedures.
The syntax for a procedure is:
Passing Parameters
When you create a procedure or function, you may define parameters. There are three types of
parameters that can be declared:
IN
The parameter can be referenced by the procedure or function. The value of the parameter
cannot be overwritten by the procedure or function.
OUT
The parameter cannot be referenced by the procedure or function, but the value of the parameter
can be overwritten by the procedure or function.
1. IN
The parameter can be referenced by the procedure or function. The value of the parameter
cannot be overwritten by the procedure or function.
2. OUT
The parameter can not be referenced by the procedure or function, but the value of the parameter
can be overwritten by the procedure or function.
3. IN OUT
The parameter can be referenced by the procedure or function and the value of the parameter
can be overwritten by the procedure or function.
BEGIN
open c1;
fetch c1 into cnumber;
if c1%notfound then
cnumber := 9999;
end if;
close c1;
RETURN cnumber;
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -
You could then reference your new function in an SQL statement as follows:
select course_name, FindCourse(course_name) as course_id
from courses
where subject = 'Mathematics';
Implementing Packages
What is a Package?
A package is a collection of Functions, Procedures, Global variables and cursors stored in server
in compiled form. A package consists of 2 parts:
Package Specification: This acts as an interface to the user applications. This part declares the,
PL/SQL types, variables, constants, exception, cursor & sub-programs (Functions and
procedures). This part is created using CREATE PACKAGE command
Package Body: It implements the specifications by defining the cursors and sub-programs. This
part is created using CREATE PACKAGE BODY command.
Oracle stores package specification and body separately in the data dictionary. A package
specification can exists without a package body but not vice versa.
The sub-programs that are present inside a package cannot exist separately as database objects.
A package cannot be called by itself. Only the procedures and functions from within the package
can be called with reference to the package using the dot (.) operator. When one sub-program is
called, then all other sub-programs are also loaded into the memory, hence the subsequent call
for any other modules becomes fast.
SUMMARY
?? A package is a compiled database objects logically groups PL/SQL types, sub-
programs etc. It consists of two parts: specification and body
?? The specification is the interface to your applications; it declares the types, variables,
constants, exceptions, cursors, and subprograms available for use. The body fully
defines cursors and subprograms, and so implements the specification
2. Create a procedure that will accept the LOAN amount and EMPNO as input and
display the installment amount and number of installments to be paid. (Max loan
amount will be his current salary * total number of years of service. Loan will be paid
in equal monthly installment. Installment amount will be 1/10th of monthly salary)
Chapter 5: Triggers
Learning Objectives
Components of Triggers
The main components of Database Triggers are the following:
?? Trigger Timing
It means when a trigger should fire. The possible trigger timing are BEFORE, AFTER
?? Trigger Event
The trigger event can be INSERT, UPDATE or DELETE
?? Trigger Type
This section specifies the action need to be performed by the trigger i.e. it is the PL/SQL block
that gets executed
Types of Triggers
There are two kinds of triggers in Oracle:
?? Row Level
–The action specified with the row level trigger will be executed for each affected row
by the instruction for which the trigger is invoked
–These triggers will fire for every INSERT/UPDATE/DELETE on the table depending
on the number of rows affected by by the triggering event
–Should specify the keyword FOR EACH ROW
?? Statement Level
–They get fired in the table level once for each trigger event
–These triggers will fire for every INSERT/UPDATE/DELETE on the table irrespective
of the number of rows affected by the triggering event
–To define a statement level trigger omit the FOR EACH ROW keyword in the trigger
specification
Create Triggers
Insert Triggers:
BEFORE INSERT Trigger:
A BEFORE INSERT Trigger means that Oracle will fire this trigger before the INSERT operation
is executed.
The syntax for a BEFORE INSERT Trigger is:
CREATE or REPLACE TRIGGER trigger_name
BEFORE INSERT
ON TABLE
[FOR EACH ROW ]
DECLARE
-- variable declarations
BEGIN
-- trigger code
EXCEPTION
WHEN ...
-- exception handling
END;
SUMMARY
?? Triggers are stored procedures that gets implicitly executed when some database-
related event occurs
?? Can work for any DML statements like INSERT, UPDATE and DELETE but not for
SELECT
?? Triggers can be row level and statement level. The action specified with the row level
trigger will be executed for each affected row by the instruction for which the trigger is
invoked
?? The statement level triggers will fire for every INSERT/UPDATE/DELETE on the table
irrespective of the number of rows affected by by the triggering event
1.Write a trigger on the EMP table, so that after each insertion of new record, or updation of old
one, the NOE column of the dept table gets updated. Add a column NOE to the dept table, which
will record the number of rows for each department. In case of record updation the NOE of one
department should be reduced and another should be incremented.
Learning Objectives
Understand Collections
What is a Collection?
A collection is an ordered group of elements, all of the same type
Features of Collection:
?? It is a general concept that encompasses list, arrays and other familiar datatypes
?? Each element has a unique subscript that determines its position in the collection
Types of Collection
PL/SQL has two collection types:
?? Tables
?? Varrays
Varrays
Items of type VARRAY are called Varrays.Allow to associate a single identifier with an entire
collection. Manipulate the collection as a whole and reference individual elements easily. To
reference an element, use standard subscripting syntax.
INDEX BY key_type;
Type_name is a type specifier used later to declare collections.
Element_type is any PL/SQL datatype.
Key_type can be numeric, either BINARY_INTEGER or PLS_INTEGER.
It can also be VARCHAR2 or one of its subtypes VARCHAR, STRING, or LONG.
You mustSpecify the size. (Varchar2 (1000);)
Syntax for Nested tables:
TYPE type_name IS TABLE OF element_type [NOT NULL];
type_name is a type specifier used later to declare collections
element_type is any PL/SQL datatype.
Syntax for Varrays:
TYPE type_name IS {VARRAY | VARYING ARRAY} (size_limit)
OF element_type [NOT NULL];
type_name and element_type are the same as for nested tables.size_limit is a
positive integer literal representing the maximum number of elements in the array
When defining a VARRAY type, must specify its maximum size.
Example, of a type that stores up to 366 dates:
DECLARETYPE Calendar IS VARRAY (366) OF DATE;
Example of Index- by Tables
DECLARE
TYPE EmpTabTyp IS TABLE OF emp%ROWTYPE /* Create a type */
INDEX BY BINARY_INTEGER;
emp_tab EmpTabTyp; /* Declaration of variable of collection type */
TYPE typ_number IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;
empid_tab typ_number; /* Declaration of variable of collection type */
BEGIN /* Retrieve employee record. */
SELECT * INTO emp_tab(7468) FROM emp WHERE empno = 7468;
SELECT EMPID
BULK COLLECT INTO empid_tab
FROM EMP;
IF empid_tab.last > 0 THEN
FORALL I in 1.. empid_tab.last
LOOP
Dbms_output.put_line(‘Empid: ‘||empid_tab(i)) END LOOP
END IF;
END;
Example of Varrays
CREATE TYPE ProjectList AS VARRAY (50) OF VARCHAR2 (16);
/
CREATE TABLE department ( -- create database table
dept_id NUMBER(2),
name VARCHAR2(15),
budget NUMBER(11,2),
-- Each department can have up to 50 projects.
projects ProjectList)
/
?? NEXT (n) - Returns the index of the next element after the specified element.
?? EXTEND - Appends a single null element to the collection.
?? EXTEND (n) - Appends n null elements to the collection.
?? EXTEND (n1, n2) - Appends n1 copies of the n2th element to the collection
?? TRIM - Removes a single element from the end of the collection.
?? TRIM (n) - Removes n elements from the end of the collection.
SUMMARY
?? A collection is a ordered group of elements, all of the same type
?? Each element has a unique subscript that determines its position in the collection
?? PL/SQL has two collection types: Tables, Varrays
?? Tables comes in two flavors Index by tables (formerly called PL/SQL tables) and
Nested Tables
?? Dynamic SQL enables to write programs that reference SQL statements whose full
text is not known until runtime
?? Before discussing dynamic SQL in detail, a clear definition of static SQL may provide
a good starting point for understanding dynamic SQL
?? Static SQL statements do not change from execution to execution. The full text of
static SQL statements are known at Compilation time that is not there in case of
Dynamic SQL
?? Dynamic SQL should be used in cases where static SQL does not support the
operation you want to perform or in cases you do not know the exact SQL statements
that must be executed by a PL/SQL procedure i.e. at Runtime
The EXECUTE IMMEDIATE statement prepares (parses) and immediately executes a dynamic
SQL statement or an anonymous PL/SQL block
Syntax
EXECUTE IMMEDIATE dynamic_string
[INTO {define_variable[, define_variable]... | record}]
–Every bind argument must be put in the USING clause. If no parameter mode is specified, it
defaults to IN. At run time, any bind arguments in the USING clause replace corresponding
placeholders in the SQL statement or PL/SQL block. So, every placeholder must be associated
with a bind argument in the USING clause. Numeric, character, and string literals are allowed in
the USING clause, but Boolean literals (TRUE, FALSE, NULL) are not. To pass nulls to the
dynamic string, a workaround must be used. Dynamic SQL supports all the SQL datatypes.
–So, for example, define variables and bind arguments can be collections, LOBs, instances of an
object type, and REFs
DECLARE
sql_stmt VARCHAR2(100);
plsql_block VARCHAR2(200);
my_deptno NUMBER(2) := 50;
my_dname VARCHAR2(15) := ’PERSONNEL’;
my_loc VARCHAR2(15) := ’DALLAS’;
emp_rec emp%ROWTYPE;
BEGIN
sql_stmt := ’INSERT INTO dept VALUES (:1, :2, :3)’;
EXECUTE IMMEDIATE sql_stmt USING my_deptno, my_dname,
my_loc;
sql_stmt := ’SELECT * FROM emp WHERE empno = :id’;
EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING 7788;
EXECUTE IMMEDIATE ’DELETE FROM dept
?? The transfer of data back and forth from PL/SQL to SQL and back again is called
context switching. The more switches occur the more performance degrades. Two
new enhancements
?? BULK COLLECT and the FORALL statements allows to bulk together all of the
context switches into a single switch and pass that to the SQL engine
?? Bulk DML using the FORALL statement will also take advantage of turning multiple
context switches into a single context switch.
The body of the FORALL statement must contain a single DML operation.
?? The DML must reference collection elements, indexed by the index_row variable in
the FORALL statement. The scope of the index_row variable is the FORALL
statement only; you may not reference it outside of that statement
?? Do not declare an INTEGER variable for index_row. It is declared implicitly by the
PL/SQL engine
?? The lower and upper bounds must specify a valid range of consecutive index
numbers for the collection(s) referenced in the SQL statement.
Example of FOR ALL:
PROCEDURE proc_bulk_collect IS
CURSOR cur_emp IS
SELECT emono
FROM emp;
TYPE tt_empno IS TABLE OF emp.empno%TYPE INDEX BY
BINARY_INTEGER;
tab_emono tt_empno;
BEGIN
OPEN cur_emp;
FETCH cur_emp INTO BULK COLLECT tab_emono;
close cur_emp;
FORALL i IN tab_emono.FIRST..tab_emono.LAST LOOP
DELETE FROM new_emp
WHERE empno = tab_emono(i);
END LOOP;
end;
PROCEDURE proc_bulk_collect IS
CURSOR cur_emp IS
SELECT emono,ename
FROM emp;
TYPE tt_empno IS TABLE OF emp.empno%TYPE INDEX BY
BINARY_INTEGER;
tab_emono tt_empno;
TYPE tt_ename IS TABLE OF emp.ename%TYPE INDEX BY
BINARY_INTEGER;
tab_ename tt_ename;
BEGIN
OPEN cur_emp;
FETCH cur_emp INTO BULK COLLECT tab_emono,tab_ename;
close cur_emp;
END;
Hard parse : It is a statement, which is parsed every time during the execution is called hard
parse. If we have to Hard Parse a large percentage of our queries, our system will function slowly
and in some cases. Hard parse can be avoided by using bind variable in subprogram.
REFERENCES
WEBSITES
?? http://otn.oracle.com
?? http://www.docnmail.com/learn/Oracle.htm
BOOKS
STUDENT NOTES: