0% found this document useful (0 votes)
40 views

Unit4 PLSQL

The document discusses PL/SQL basics including its advantages over SQL, the structure of a PL/SQL block with declare, begin, exception, and end sections, data types in PL/SQL, variables, constants, and literals.

Uploaded by

Prajwal Poojary
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Unit4 PLSQL

The document discusses PL/SQL basics including its advantages over SQL, the structure of a PL/SQL block with declare, begin, exception, and end sections, data types in PL/SQL, variables, constants, and literals.

Uploaded by

Prajwal Poojary
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

PL/SQL UNIT - IV

PL/SQL Basics
Introduction to PL/SQL
Though SQL is the natural language of the DBA, it suffers from various inherent
disadvantages, when used as a conventional programming language.
1. SQL does not have any procedural capabilities i.e. SQL does not provide the programming
techniques of condition checking, looping and branching that is vital for data testing before
its permanent storage.
2. SQL statements are passed to the Oracle Engine one at a time. Each time an SQL statement is
executed, a call is made to the engine’s resources. This adds to the traffic on the network,
thereby decreasing the speed of data processing, especially in a multi-user environment.
3. While processing an SQL sentence if an error occurs, the Oracle engine displays its own error
messages. SQL has no facility for programmed handling of errors that arise during the
manipulation of data.
Although SQL is a very powerful tool, its set of disadvantages prevent, it from being a fully
structured programming language. For a fully programming language, Oracle provides PL/SQL.
As the name suggests, PL/SQL is a superset of SQL. PL/SQL is a block-structured language
that enables developers to combine the power of SQL with procedural statements. PL/SQL bridges
the gap between database technology and procedural programming languages.

Advantages of PL/SQL
1. PL/SQL is development tool that not only supports data manipulation but also provides
facilities of conditional checking, branching and looping.
2. PL/SQL sends an entire block of SQL statements to the Oracle engine all in one go.
Communication between the program block and the Oracle engine reduces considerably,
reducing network traffic. Since the Oracle engine got the SQL statements as a single block, it
processes this code much faster than if it got the code one sentence at a time. There is a
definite improvement in the performance time of the Oracle engine. As an entire block of
SQL code is passed to the Oracle engine at one time for execution, all changes made to the
data in the table are done or undone in one go.
3. PL/SQL also permits dealing with errors as required, and facilities displaying user-friendly
messages, when errors are encountered.
4. PL/SQL allows declaration and use of variables in blocks of code. These variables can be
used to store intermediate results of a query for later processing, or calculate values and insert
them into an Oracle table later. PL/SQL variable can be used anywhere, either in SQL
statements or in PL/SQL blocks.
5. Via PL/SQL, all sorts of calculations can be done quickly and efficiently without the use of
the Oracle engine. This considerably improves transaction performance.
6. Applications written in PL/SQL are portable to any computer hardware and operating system,
where Oracle is operational. Hence, PL/SQL code blocks written for a DOS version of Oracle
will run on its Linux/UNIX version, without any modifications at all.

The generic PL/SQL Block


Every programming environment allows the creation of structured, logical blocks of code that
describe processes, which have to be applies to data. Once these blocks are passed to the
environment, the processes described are applied to data, suitable data manipulation takes place, and
useful output is obtained.
PL/SQL permits the creation of structured logical blocks of code that describe processes, which have
to be applied to data. A single PL/SQL code block consists of a set of SQL statements, clubbed
together, and passed to the Oracle engine entirely. This block has to be logically grouped together
for the engine to recognize it as a singular code block. A PL/SQL block has a definite structure,
which can be divided into sections. The sections of a PL/SQL blocks are:
 The Declare section
 The Master Begin and End section that also (optionally) contains an Exception section.
Each of these is explained below:

Sri Ramakrishna College, Mangaluru. Page 1


PL/SQL UNIT - IV
The Declare Section
Code blocks start with a declaration section, in which, memory variables and other Oracle
objects can be declared, and if required initialized. Once declared, they can be used in SQL
statements for data manipulation.

The Begin Section


It consists of a set of SQL and PL/SQL statements, which describe processes that have to be
applied to table data. Actual data manipulation, retrieval, looping and branching constructs are
specified in this section.

The Exception Section


This section deals with handling of errors that arise during execution of the data manipulation
statements, which make up the PL/SQL code block. Errors can rise due to syntax, logic and/or
validation rule violation.

The End Section


This marks the end
DECLARE Declarations of memory variables, constants,
of a PL/SQL block.
cursors, etc. in PL/SQL
A PL/SQL code block
BEGIN SQL executable statements PL/SQL executable
can be diagrammatically
statements.
represented as follows:
EXCEPTION SQL or PL/SQL code to handle errors that may
arise during the execution of the code block
between BEGIN and EXCEPTION section
END;
The Character Set
The basic character set includes the following:
 Uppercase alphabets {A – Z}
 Lowercase alphabets {a – z}
 Numerals {0-9}
 Symbols ( ) + -* / < > =! ; : . ‘ @ % , “ # $ ^ & _ \ { } ? []
Words used in a PL/SQL block are called Lexical Units. Blank spaces can be freely inserted
between lexical units in a PL/SQL block. The blank spaces have no effect on the PL/SQL block.

The ordinary symbols used in PL/SQL blocks are:


( ) + - * / < > = ; % ‘ “ [ ] :

Compound symbols used in PL/SQL blocks are:


< > != ~= ^= <= >= := ** .. || << >>

Literals
A literal is a numeric value or a character string used to represent itself.

Numeric Literal
These can be either integers or floats. If a float is being represented, then the integer part must be
separated from the float part by a period.

String Literal
These are represented by one or more legal character and must be enclosed within single
quotes. The single quote character can be represented, by writing it twice in a string literal. This is
definitely not the same as a double quote.

Character Literal
These are string literals consisting of single characters.

Logical (Boolean) Literal

Sri Ramakrishna College, Mangaluru. Page 2


PL/SQL UNIT - IV
These are predetermined constants. The values that can be assigned to this data type are:
TRUE, FALSE, NULL.

PL/SQL Data Types


Both PL/SQL and Oracle have their foundations in SQL. Most PL/SQL data types are native to
Oracles data dictionary. Hence, there is a very easy integration of PL/SQL code with the Oracle
Engine.
The default data types that can be declared in PL/SQL are number (for storing numeric data), char
(for storing string character data), date (for storing date and time data), Boolean (for storing TRUE,
FALSE or NULL), number, char and date data types can have NULL values.

The %TYPE attribute provides for further integration. PL/SQL can use the %TYPE attribute to
declare variables based on definitions of columns in a table. Hence, if a column’s attribute change,
the variables attributes will change as well. This provides for data independence, reduces
maintenance costs, and allows programs to adapt to changes made to the table.

%TYPE declares a variable or constant to have the same data type as that of a previously defined
variable or of a column in a table or in a view. When referencing a table, a user may name the table
and column, or name the owner, the table and the column.

NOT NULL causes creation of a variable or a constant that cannot be assigned a null value. If an
attempt is made to assign the value NULL to a variable or a constant that has been assigned a NOT
NULL constraint, Oracle senses the exception condition automatically and an internal error is
returned.

Variables
Variables in PL/SQL blocks are named variables. A variable name must begin with a
character and can be followed by a maximum of 29 other characters.
Reserved words cannot be used as variable names unless enclosed within double quotes. Variables
must be separated from each other by at least one space or by a punctuation mark.
Case is insignificant when declaring variable names. A space cannot be used in a variable name. A
variable of any data type either native to the Oracle Engine such as number, char, date, and so on or
native to PL/SQL such as Boolean (i.e. logical variable content) can be declared.

Assigning Values to Variables


The assigning of a value to a variable can be done in two ways:
 Using the assignment operator : = (i.e. a colon followed by an equal to sign).
 Selecting or fetching table data values into variables.

Constants
Declaring a constant is similar to declaring a variable expect that the keyword constant must
be added to the variable name and a value assigned immediately. Thereafter, no further assignments
to the constants are possible, while the constant is within the scope of the PL/SQL block.

Raw
Raw types are used to store binary data. Character variables are automatically converted between
character sets by Oracle, if necessary. These are similar to char variables, except that they are not
converted between character sets. It is used to store fixed length binary data. The maximum length
of a raw variable is 32,767 bytes. However, the maximum length of a database raw column is 255
bytes.

Long raw is similar to long data, except that PL/SQL will not convert between character sets. The
maximum length of a long raw variable is 32,760 bytes. The maximum length of a long raw column
is 2 GB.

Rowid
This data type is the same as the database ROWID pseudo-column type. It can hold a rowid, which
can be considered as a unique key for every row in the database. Rowids are stored internally as a
fixed length binary quantity, whose actual fixed length varies depending on the operating system.
Sri Ramakrishna College, Mangaluru. Page 3
PL/SQL UNIT - IV

Various DBMS_ROWID functions are used to extract information about the ROWID pseudo-
column. Extended and Restricted are two rowid formats. Restricted is used mostly to be backward
compatible with previous versions of Oracle. The Extended format takes advantage of new Oracle
features.

Displaying User Messages On The VDU Screen


Programming tools require a method through which messages can be displayed on the VDU screen.

DBMS_OUTPUT is a package that includes a number of procedures and functions that accumulate
information in a buffer so that it can be retrieved later. These functions can also be used to display
messages.

PUT_LINE puts a piece of information in the package buffer followed by an end-of-line marker. It
can also be used to display a message. PUT_LINE expects a single parameter of character data type.
If used to display a message, it is the message string.

To display messages, the SERVEROUTPUT should be set ON. SERVEROUTPUT is a SQL *


PLUS environment parameter that displays the information passed as a parameter to the PUT_LINE
function.
Syntax:
SET SERVEROUTPUT [ON/OFF]

CONTROL STRUCTURE

The flow of control statements can be classified into the following categories:
 Conditional Control
 Iterative Control
 Sequential Control

Conditional Control
PL/SQL allows the use of an IF statement to control the execution of a block of code. In PL/SQL,
the IF-THEN-ELSIF-ELSE-END IF construct in code blocks allow specifying certain conditions
under which a specific block of code should be executed.

Syntax:
IF <Condition> THEN
<Action>
ELSIF <Condition> THEN
<Action>
ELSE
<Action>
END IF;
Example:-

Sri Ramakrishna College, Mangaluru. Page 4


PL/SQL UNIT - IV
Iterative Control
Iterative control indicates the ability to repeat or skip sections of a code block. A loop marks a
sequence of statements that has to be repeated. The keyword loop has to be placed before the first
statement in the sequence of statements to be repeated, while the keyword end loop is placed
immediately after the last statement in the sequence. Once a loop begins to execute, it will go on
forever. Hence a conditional statement that controls the number of times a loop is executed always
accompanies loops.

PL/SQL supports the following structure for iterative control:

Simple Loop
In simple loop, the key word loop should be placed before the first statement in the sequence and the
keyword end loop should be written at the end of the sequence to end the loop.
Syntax:
LOOP
<Sequence of Statement>
END LOOP;
Example:-
Creating a simple loop such that a message is displayed when a loop exceeds a particular value.
DECLARE
i number :=0;
BEGIN
LOOP
i := i + 2;
EXIT WHEN i>10;
END LOOP;
dbms_output.put_line(‘Loop exited as the value of I has reached ’|| to_char(i));
END;
The WHILE loop
Syntax:
WHILE <Condition>
LOOP
<Action>
END LOOP;
Example:-
SET SERVEROUTPUT ON
DECLARE
counter INTEGER := 2;
BEGIN
counter := 0;
WHILE counter < 6
LOOP
counter := counter + 1;
DBMS_OUTPUT.PUT_LINE(counter);
END LOOP;
END;
/

The FOR Loop


Syntax:
FOR variable IN [REVERSE] start… end
LOOP
<Action>
END LOOP;

Sri Ramakrishna College, Mangaluru. Page 5


PL/SQL UNIT - IV
Note: The variable in the For Loop need not be declared. Also the increment value cannot be
specified. The For Loop variable is always incremented by 1.
Example:-
DECLARE i NUMBER := 5;
BEGIN
FOR i IN 1..3 LOOP
DBMS_OUTPUT.PUT_LINE ('Inside loop, i is ' || TO_CHAR(i));
END LOOP;
DBMS_OUTPUT.PUT_LINE ('Outside loop, i is ' || TO_CHAR(i));
END;
/

PL/SQL TRANSACTIONS

PROCESSING A PL/SQL BLOCK


A PL/SQL block can be run in one of two modes
 Batch processing wherein records are gathered in a table and at regular intervals manipulated
 Real time processing wherein records are manipulated as they are created

Batch processing is a PL/SQL block run at the SQL prompt at regular intervals to process table data.
A technique that Oracle provides for manipulating table data in batch processing mode is the use at
cursors.

Oracle and the processing of SQL statements


Whenever an SQL statement is executed, Oracle engine performs the following tasks:
 Reserves a private SQL area in memory
 Populates this area with the data requested in the SQL sentence
 Processes the data in this memory area as required
 Frees the memory area when the processing of data is complete

WHAT IS A CURSOR?
The Oracle engine uses a work area for its internal processing in order to execute an SQL statement,
this work area is private to SQL’s operations and is called a cursor.

The data that is stored in the cursor is called the active data set. Conceptually, the size of the
cursor in memory is the size required to hold the number of rows in the active data set. The actual
size however is determined by the Oracle engines built in memory management capabilities and the
amount of RAM available. Oracle has a pre-determined area in main memory set aside, within
which cursors are opened. Hence the cursors size will be limited by the size of this pre-determined
area.

The values retrieved from a table are held in a cursor opened in memory by the Oracle engine. This
data is then transferred to the client machine via the network. In order to hold this data, a cursor is
opened at the client end. if the number of rows returned by the Oracle engine is more than the area
available in the cursor opened on the client, the cursor data and the retrieved data is swapped the
operating system’s swap area and RAM.

TYPES OF CURSORS:
Cursors are classified depending on the circumstances under which they are opened. If the
Oracle engine opened a cursor for its internal processing it is known as implicit cursor. A cursor
can also be opened for processing data through a PL/SQL block, on demand. Such a user-defined
cursor is known as an explicit cursor.

General cursor attributes:

Sri Ramakrishna College, Mangaluru. Page 6


PL/SQL UNIT - IV
When the Oracle engine creates an implicit or explicit cursor control variables are also created to
control the execution of the cursor. These are a set of four system variables which keep track of the
Current status of a cursor. These cursor variables can be accessed and used in a PL/SQL code
block.

Both implicit and explicit cursors have four attributes. They are described below:
Attribute name Description
%ISOPEN Returns TRUE if the cursor is open, FALSE otherwise.
%FOUND Returns TRUE if record was fetched successfully, FALSE
otherwise.

%NOTFOUND Returns TRUE if record was not fetched successfully, FALSE


otherwise

%ROWCOUNT Returns number of records processed from the cursor.


Example:
declare
ncustno number(5);
nname varchar2(20);
begin
ncustno:=&ncustno;
select custname into nname from customer where custid=ncustno;
if sql%rowcount=1 then
insert into operation values(ncustno,'One Row Found');
end if;
exception
when no_data_found then
insert into operation values(ncustno,'No Data Found');
when too_many_rows then
insert into operation values(ncustno,'Multiple Rows Found');
end;

Implicit Cursor
The Oracle engine implicitly opens a cursor on the Server to process each SQL statement. Since the
implicit cursor is opened and managed by the Oracle engine internally, the function of reserving an
area in memory, population this area with appropriate data, processing the data in the memory area,
releasing the memory area when the processing is complete is taken care of by the Oracle engine.
The resultant data is then passed to the client machine via the network. A curser is then opened in
memory on the client machine to hold the row returned by the Oracle engine. The number of rows
held in the cursor on the client is managed by the client’s operating system and its swap area.
Implicit cursor attributes can be used to access information about the status of the last
insert, update, delete or single-row select statements. This can be done by preceding the implicit
cursor attribute with the cursor name (i.e. SQL).the values of the cursor attributes always refer to the
most recently executed SQL statement wherever that statement appears. If an attribute value is to be
saved for later use, it must be assigned to a (Boolean) memory variable.

Implicit cursor attributes


Attribute name Description
%ISOPEN The Oracle engine automatically opens and closes the SQL cursor after
executing associated select, insert, update or delete SQL statement has
been processed in case of implicit cursors. Thus the SQL%ISOPEN
attribute of an implicit cursor cannot be referenced outside of its SQL
statement. As result, SQL%ISOPEN always evaluates to FALSE.

%FOUND Evaluates to TRUE, if an insert, update or delete affected one or more


rows, or a single-row select returned one or more rows. Otherwise it
evaluates to FALSE. the syntax for accessing this SQL%FOUND

Sri Ramakrishna College, Mangaluru. Page 7


PL/SQL UNIT - IV
%NOTFOUND Is a logical opposite of %FOUND. it evaluates to TRUE, if an insert,
update or delete affected no rows, or a single-row select returns no rows.
otherwise, it evaluates to false. the syntax for accessing this attribute is
SQL%NOTFOUND
%ROWCOUNT Returns the number of rows affected by an insert, update or delete, or
select into statement the syntax for accessing this attribute is
SQL%ROWCOUNT

Explicit cursor
When individual records in a table have to be processed inside a PL/SQL code block a cursor is
used. This cursor will be declared and mapped to an SQL query in the declare section of the PL/SQL
block and used within its executable section. a cursor thus created and used is known as an explicit
cursor.

Explicit cursor management


The steps involved in using an explicit cursor and manipulating data in its active set are:
 Declare a cursor mapped to a SQL select statement that retrieves data from processing
 Open the cursor
 Fetch data from cursor one row at a time into memory variables
 Process the data held in the memory variables as required using a loop.
 Exit from the loop after processing is complete
 Close the cursor

Cursor declaration
A cursor is defined in a declarative part of a PL/SQL block. This is done by naming the cursor and
mapping it to a query. When a cursor is declared the Oracle engine is informed that a cursor of the
said name is to be opened. The declaration is only intimation. There is no memory allocation at this
point in time. The three commands used to control the cursor subsequently are open, fetch and close.

The functionality of open, fetch and close commands


Initialization of a cursor takes place via the open statement, this:
 Defines a private SQL area named after the cursor name
 Executes a query associated with the cursor
 Retrieves table data and populates the named private SQL area in memory i.e. creates the
Active Data Set
 Sets the cursor row pointer in the Active Data Set to the First record

A fetch statement then moves the data held in the active data set into memory variables. Data held in
the memory variables can be processed as desired
The fetch statement is placed inside a loop…..end loop construct, which causes the data to be
fetched into the memory variables are processed until all the rows in the active data set are
processed. The fetch loop exists. The existing of the fetch loop is user controlled.
After the fetch loop exists the cursor must be closed with close statement. This will release the
memory occupied by the cursor and its active data set. A PL/SQL block is necessary to declare a
cursor and create an active data set. The cursor name is used to reference the active data set held
within the cancer.
Syntax:
CURSOR CursorName IS SELECT statement;

Opening A Cursor
Opening a cursor executes the query and creates the active set that contains all rows, which meet the
query search criteria. An open statement retrieves records from a database table and places the
records in the cursor. A cursor is opened in the server’s memory.
Syntax:
OPEN cursorName;

Fetching a Record from The Cursor

Sri Ramakrishna College, Mangaluru. Page 8


PL/SQL UNIT - IV
The fetch statement retrieves the rows from the active set opened in the server into memory
variables declared in the PL/SQL code block on the client one row at a time. The memory variables
are opened on the client machine. Each time a fetch is executed, the cursor pointer is advanced to the
next row in the active data set.

A standard loop structure (loop-end loop) is used to fetch records from the cursor into memory
variables one row at a time.
Syntax:
FETCH cursorName INTO variable1, variable2…;

Closing A Cursor
The close statement disables the cursor and the active set becomes undefined. This will release the
memory occupied by the cursor and its Data Set both on the Client and on the Server.
Syntax:
CLOSE CursorName;

Explicit cursor attributes


Similar to the cursor attributes in case of implicit cursors, four attributes are associated with explicit
cursors. The attributes can be used in a PL/SQL code block for processing of data or exiting. The
cursor name is appended to the attribute name when referencing the attribute.

Attribute name Description


%FOUND Evaluates to TRUE, if the last fetch succeeded because a row was
available; or to FALSE if the fetch failed because no more rows were
available. The syntax for accessing this attribute is
CursorName%FOUND.
%NOTFOUND Is the logical opposite of %FOUND. It evaluates to TRUE, if the fetch
has failed because no more rows were available; or to FALSE, if the last
fetch returned a row. The syntax for accessing this attribute is
CursorName%NOTFOUND.
%ISOPEN Evaluates to TRUE, if an explicit cursor is open; or to FALSE, if it is
closed. The syntax for accessing this attribute is cursorName%ISOPEN.

%ROWCOUNT Returns the number of rows fetched from the active set. It is set to zero
when the cursor is opened. the syntax foe accessing this attribute is
CursorName%ROWCOUNT.

CURSOR FOR LOOPS


Another technique commonly used to control the loop…End loop within a PL/SQL block is the FOR
variable IN value construct. This is an example of a machine defined loop exit i.e. when all the
values in the FOR construct are exhausted looping stops.
Syntax:
FOR memory variable IN CursorName
Here, the verb FOR automatically creates the memory variable of thee %rowtype.Each record in the
opened cursor becomes a value for the memory variable of the %rowtype.
The FOR verb ensures that a row from the cursor is loaded in the declared memory variable and the
loop executes once. This goes on until all the rows of the cursor have been loaded into memory
variable. After this loop stops.
A cursor for loop automatically does the following:
 Implicitly declares its loop index as a %rowtype record
 Opens a cursor
 Fetches a row from the cursor from each loop iteration
 Closes the cursor when all rows have been processed
A cursor can be closed even when an exit or a goto statement is used to leave the loop prematurely,
or if an exception is raised inside the loop.

Sri Ramakrishna College, Mangaluru. Page 9


PL/SQL UNIT - IV
PARAMETERIZED CURSORS
Till now all the cursors that have been declared and used fetch a pre-determined set of records.
Records which satisfy conditions, set in the WHERE clause of the SELECT statement mapped to
the cursor. In other words, the criterion on which the Active Data Set is determined is hard coded
and never changes.
Commercial applications require that the query, which defines the cursor, be generic and the data
that is retrieved from the table be allowed to change according to need.
Oracle recognizes this and permits the creation of parameterized cursor which will constantly
change depending upon the value passed to its parameter.

Since the cursor accepts user-defined value into its parameters, thus changing the result set a
extracted, it is called Parameterized cursor.

Declaring A Parameterized Cursor


Syntax:
CURSOR cursorName (VariableName datatype) IS <SELECT statement…>

Opening A Parameterized cursor and passing Values to the Cursor

Syntax:
OPEN CursorName (Value/Variable/Expression)

Error Handling
PL/SQL implements error handling with exception handlers. Exception can be associated
with Oracle errors or with our own user defined errors.
Errors are classified as compile time and run-time. Exceptions are designed for runtime error
handling. Errors that occur during compilation phase are detected by the PL/SQL engine and
reported back to the user.

Declaring Exception
Exception are declared in the declarative section of the block, raised in the executable section
and handled in the exception section there are two types of exceptions user-defined and predefined.

Predefined Exception
Oracle has predefined several exceptions that correspond to the most common Oracle errors
and are called named exception handlers. The Oracle engine has about 15 to 20 named exception
handlers. In addition to this Oracle engine uses more than 20,000 numbered exception handlers.
These exception handlers are identified not by names but by 4 integers preceded by a hyphen i.e., -
1414.
Oracle named Exception handlers
The Oracle engine has a set of Pre-defined Oracle handlers called Named Exceptions.
These error handlers are referenced by their name. The following are some of the pre-defined
Oracle named exception handlers.
Pre-determined internal PL/SQL exceptions:
DUP_VAL_ON_INDEX Raised when an insert or update attempts to create two rows
with duplicate values in column/s constrained by unique
index.
LOGIN_DENIED Raised when an invalid username/password was used to log
onto Oracle.
NO_DATA_FOUND Raised when a select statement returns zero rows
NOT_LOGGED_ON Raised when PL/SQL issues an Oracle call without being
logged onto Oracle.
PROGRAM_ERROR Raised when PL/SQL has an internal problem.
TIMEOUT_ON_RESOURCE Raised when Oracle has been waiting to access a resource
beyond the user-defined timeout limit.

Sri Ramakrishna College, Mangaluru. Page 10


PL/SQL UNIT - IV
TOO_MANY_ROWS Raised when a select statement returns more than one row
VALUE_ERROR Raised when the data type or data size is invalid
OTHERS Stands for all other exception not explicitly named.

Some of the numbered exception handlers


Oracle Error Equivalent Exception
ORA-0001 DUP_VAL_ON_INDEX
ORA-0061 TRANSACTIN_BACKED_OUT
ORA-1001 INVALED_CURSOR
ORA-1403 NO_DATA_FOUND
ORA-1017 LOGIN_DEFINED

Handling exceptions
When an exception is raised control passes to the exception section of the block. The exception
handler contains the code that is executed when the error associated with the exception occurs and
the exception is raised.
Syntax:
EXCEPTION
WHEN exception_name THEN
Sequence_of_statement;
WHEN exception_name THEN
Sequence_of_statement;
WHEN other THEN
Sequence_of_statement;
END;
The WHEN clause identifies which exception this handlers is for. The OTHERS exception handlers
will execute for all raised exception. The two functions which can be used in OTHERS clause is
SQL CODE and SQLERRM, SQL CODE returns the current error code and SQLERRM returns the
current error message text.

The EXCEPTION_INIT PRAGMA


This is used to find a numbered exception handler to a name using PRAGMA EXCEPTION_INIT().
The PRAGMA action word is a call to a pre compiler, which immediately finds the numbered
exception handler to a name when encountered.

The function EXCEPTION_INIT () takes two parameter the first is the user defined exception name
the second is the Oracle engines exception no.
Syntax
DECLARE
Excepton_name EXCEPTION;
PRAGMA EXCEPTION_INIT (exception name, error_code)

Using this it is possible to find appropriate numbered exception handlers to names and use these
names in the exception section of a PL/SQL block.

Example:
DECLARE
-------------
RESOURCE_BUSY EXCEPTION;
PRAGMA EXCEPTION_INIT (RESOURCE_BUSY,-00054);
BEGIN
--------
EXCEPTION
WHEN RESOURCE_BUSY THEN
DBMS_OUTPUT.PUT_LINE (‘The row is in use’);
END;

Using RAISE_APPLICATION_ERROR

Sri Ramakrishna College, Mangaluru. Page 11


PL/SQL UNIT - IV
You can use the built-in function RAISE_APPLICATION_ERROR to create you own error
message, which can be more descriptive than named exceptions.
Syntax
RAISE_APPLICATION_ERROR (error_no, error_message, [keep_error]);
Where error_no is a parameter between 20,000 and -20,999, error_message is the text associated
with this error and keep_error is a Boolean value, the error message parameter must be fewer then
512 character.
IF salary>1000 THEN
RAISE_APPLICATION_ERROR (-20,000,’Salary greater than 1000’);
END IF;

User defined exception handling [for business rule validations]


A user defined exception is an error i.e. defined by the program. To trap business rules being
violated the technique of raising rules defined exceptions and then handling them is used.
User defined error conditions must be declared in the declarative part of any PL/SQL
block. In the executable part, a check for the condition that needs special attention is made. If that
condition exists the call to user-defined exception is made using a RAISE statement. The exception
once raise is then handled. The exception once raise is then handled in the exception handling
section of the PL/SQL code block.
Syntax
DECLARE
<exception name> EXCEPTION;
BEGIN
SQL Statement;
IF <condition> THEN
RAISE <exception name>;
END IF;
EXCEPTION
WHEN <exception name> THEN
User defined action to be taken;
END;

PL/SQL DATABASE OBJECTS


What are procedure/functions?
A procedure or function is a logically grouped set of SQL and PL/SQL statements that perform
a specific task. A stored procedure or function is a named PL/SQL code block that has been
compiled and stored in one of the Oracle engine’s system tables.

To make a Procedure or Function dynamic either of them can be passed parameters before
execution. A Procedure or Function can then change the way it works depending upon the
parameters passed prior to its execution.

Procedures and functions are made up of:


 A declarative part
 An executable part
 An optional execution-handling part

Declarative Part
The declarative part may contain the declarations of cursors, constants, variables, exceptions and
subprograms. These objects are local to the procedure or function. The objects become invalid once
the procedure or function exits.

Executable Part
The executable part is a PL/SQL block consisting of PL/SQL statements that assign values, control
execution and manipulate data. The action that the procedure or function is expected to perform is
coded here. The data that is to be returned back to the calling environment is also returned from
here. The variables declared are put to use within this block.

Exception Handling Part

Sri Ramakrishna College, Mangaluru. Page 12


PL/SQL UNIT - IV
This part contains code that deals with exceptions that may be raised during the execution of code in
the executable part. An Oracle exception handler can be redirected to the exception handling section
of the procedure or function where the procedure or function determines the actual action that must
be carried out by Oracle’s exception handler.
The flow of code execution from the Exception Handling part cannot be transferred to the
Executable part.

WHERE DO STORED PROCEDURES AND FUNCTIONS RESIDE?


Procedures and Functions are stored in the Oracle database. They can be invoked or called by any
PL/SQL block that appears within an application. Before a procedure or function is stored, the
Oracle engine parses and compiles the procedure or function.

How Does The Oracle Engine Create A Stored Procedure/Function?


The following steps are performed automatically by the Oracle engine while creating a procedure:
 Compiles the procedure or function
 Stores the procedure or function in the database
The Oracle engine combines the PL/SQL code block. If an error occurs during the compilation of
the procedure or function, an invalid procedure or function gets created. The Oracle engine displays
a message after creation that the procedure or function was created with compilation errors.

The compilation process does not display the errors. These errors can be viewed using the
SELECT statement:
SELECT * FROM USER_ERRORS;

When a procedure or function is invoked, the Oracle engine loads the compiled procedure or
function in a memory area called the System Global Area (SGA). This allows the code to be
executed quickly. Once loaded in the SGA other users also access the same procedure or function if
they have been granted permission to do so.

How Does The Oracle Engine Execute Procedures/Functions?


The Oracle engine performs the following steps to execute a procedure or function:
 Verifies user access
 Verifies procedure or function validity
 Executes the procedure or function

The Oracle engine checks if the user who called the procedure or function has the execute privilege
for the procedure or function. If the user is invalid, then access is denied otherwise the Oracle engine
proceeds to check whether the called procedure or function is valid or not. The status of a procedure
or function is shown by the use of a SELECT statement as follows:
SELECT <ObjectName>, <ObjectType>, <Status>FROM <UserObjects>
WHERE <ObjectType>=<’PROCEDURE’>;
Or
SELECT <Object_Name>, <Object_Type>, <Status> FROM <User_Objects>
WHERE <Object_Type>=<’FUNCTION’>;
Only if the status is valid, will a procedure or function be executed. Once found valid, the Oracle
engine then loads a procedure or function into memory (i.e. if it is not currently passed in memory)
and executes it.

ADVANTAGES OF USING A PROCEDURE OR FUNCTION


Security
Stored procedures and functions can help enforce data security. For e.g. by giving permission to a
procedure or function that can query a table and granted the procedure or function to users,
permissions to manipulate the table itself need not be granted to users.

Performance
It improves database performance in the following ways:
 Amount of information sent over a network is less
 No compilation step is required to execute the code

Sri Ramakrishna College, Mangaluru. Page 13


PL/SQL UNIT - IV
 Once the procedure or function is present in the shared pool of the SGA retrieval from disk is
not required every time different users call the procedure or function i.e. reduction in disk I/O

Memory Allocation
The amount of memory used reduces as stored procedures or functions have shared memory
capabilities. Only one copy of procedure needs to be loaded for execution by multiple users. Once a
copy of a procedure or function is opened in the Oracle engine’s memory, other users who have
appropriate permission may access it when required.

Productivity
By writing procedures and functions redundant coding can be avoided, increasing productivity.

Integrity
A procedure or function needs to be tested only once to guarantee that it returns an accurate result.
Since procedures and functions are stored in the Oracle engine they become the part of the engine’s
resource. Hence the responsibility of maintaining their integrity rests with the Oracle engine. The
Oracle engine has the high level of in-built security and hence integrity of procedures or function
can be safely left to the Oracle engine.

PROCEDURES VERSES FUNCTIONS


The differences between Procedures and Functions can be listed as below:
 A function must return a value back to the caller. A function can return only one value to the
calling PL/SQL code block.
 By defining multiple OUT parameters in a procedure, multiple values can be passed to the
caller. The OUT variable being global by nature, its value is accessible by any PL/SQL code
block including the PL/SQL block via which it was called

Creating Stored Procedure


Syntax:
CREATE OR REPLACE PROCEDURE [schema.]<ProcedureName>
(<Argument>{IN,OUT,IN OUT}<Data type>,…….){IS,AS}
<Variable> declarations;
<Constant> declarations;
BEGIN
<PL/SQL subprogram body>;
EXCEPTION
<Exception PL/SQL block>;
END;

Keywords and Parameters


The keywords and the parameters used for the creating database procedures are explained below:
Recreates the procedure if it already exits. This option is used to change the
definition of an existing procedure without dropping, recreating and re-granting
REPLACE
object privileges previously granted on it. If a procedure is redefined the Oracle
engine recompiles it.

Is the schema to contain the procedure. The Oracle engine takes the default
Schema
schema to be the current schema, if it is omitted.
Procedure Is the name of the procedure to be created.
Is the name of an argument to the procedure. Parentheses can be omitted if no
Argument
arguments are present.
IN Indicates that the parameter will accept a value from the user.
OUT Indicates that the parameter will return a value to the user
Indicates that the parameter will either accept a value from the user or return a value to
IN OUT
the user.
Data type Is the data type of an argument. It supports any data type supported by PL/SQL.

Sri Ramakrishna College, Mangaluru. Page 14


PL/SQL UNIT - IV
PL/SQL
Subprogram Is the definition of procedure consisting of PL/SQL statements.
Body

Creating A Functions
Syntax:
CREATE OR REPLACE FUNCTION [Schema.]<FunctionName>
(<Argument> IN <Data Type>,……)
RETURN <Data Type> {IS, AS}
<Variable> Declarations;
<Constant> Declarations;
BEGIN
<PL/SQL subprogram body>;
EXCEPTION
<Exception PL/SQL block>;
END;

Keywords and Parameters


The keywords and the parameters used for creating database functions are explained below:
Recreates the function if it already exists. This option is used to change the definition of
an existing function without dropping, recreating and re-granting object privileges
REPLACE previously granted on it. If a function is redefined, Oracle recompiles it.

Is the schema to contain the function. Oracle takes the default schema to be the current
Schema schema, if it is omitted.
Function Is the name of the function to be created.
Is the name of an argument to the function. Parenthesis can be omitted if no argument s
Argument are present.
IN Indicates that the parameter will accept a value from the user
RETURN Data Is the data type of the function’s return value. Because every function must return a
type value, this clause is required. It supports any data type supported by PL/SQL.
PL/SQL Is the definition of function consisting of PL/SQL statements.
Subprogram
Body

Using A Function
CREATE or REPLACE FUNCTION f_chkitem(vitemno in number)
RETURN NUMBER IS
dummyitemno number(10);
BEGIN
SELECT itemno INTO dummyitemno FROM item_master
WHERE itemno=vitemno;
RETURN 1;
EXCEPTION
WHEN no_data_found THEN RETURN 0;
END;

DECLARE
nitem_no NUMBER(10);
nqty NUMBER(4);
BEGIN
nitem_no:=&nitem_no;
nqty:=&nqty;
IF f_chkitem(nitem_no) = 1 THEN
INSERT INTO item_trans VALUES(nitem_no,nqty,sysdate);
COMMIT;
ELSE
DBMS_output.put_line('item does not exist');
END IF;
END;

Sri Ramakrishna College, Mangaluru. Page 15


PL/SQL UNIT - IV
Consider the tables ITEM_MSTR and ITEM_TRANS. The ITEM_TRANS table is used to
register the item transactions as performed. As a batch process, the initial item transaction must be
written to the ITEM_TRANS table whenever an item is present in the item master table.
To help simplify this process (of batch insertion) a function called f_ChkAcctNo has been created.
The function checks for the existence of ITEM_NO in the table ITEM_MSTR. The function has one
argument, which receives a value. The function will search for a matching value in the
ITEM_MSTR table when a value is passed to it when being invoked.
The function will return 1 indicating that a match is found or 0 indicating that no match is found.
This value returned by the function is used to make a decision to insert a record or display no of item
present.
Creating Function For Use
A stored function is created to perform the ACCT_NO check operation. f_ChkAcctNo() is the name
of the function which accepts a variable ACCT_NO and returns a value to the host environment. The
value changes from 0 (i.e. if ACCT_NO does not exist) to 1 (i.e. if ACCT_NO exists) depending on
the records retrieved.

FINALLY A COMMIT IS FIRED TO REGISTER THE CHANGES


DELETING A STORED PROCEDURE OR FUNCTION
A procedure or function can be deleted by using the following syntax
Syntax:
DROP PROCEDURE <ProcedureName>;
Example:
DROP PROCEDURE PROC_INSUPD;
Output:
Procedure dropped

Syntax:
DROP FUNCTION <FunctionName>;
Example:
DROP FUNCTION F_CHKACCTNO;
Output:
Function dropped.

ORACLE PACKAGES
A package is an Oracle object, which holds other objects within it. Objects commonly held within a
package a procedures, functions, variables, constants, cursors and exceptions. The tool used to create
a package is SQL*plus. It is a way of creating a generic, encapsulated, re-useable code.
A package once written and debugged is compiled and stored in Oracle’s system tables held in an
Oracle Database. All users who have executed permissions on the Oracle Database can then use the
package.
Packages can contain PL/SQL blocks of code, which have been written to perform some process
entirely on their own. These PL/SQL blocks of code do not require any kind of input from other
PL/SQL blocks of code. These are the package’s standalone subprograms.
Alternatively, a package can contain a subprogram that requires input from another PL/SQL block to
perform its programmed process successfully. These are subprograms of the package but these
subprograms are not standalone.
Subprograms held within a package can be called from other stored programs, like triggers,
precompilers, or any other Interactive Oracle program like SQL*plus.
Components of an Oracle package
A package has usually two components, a specification and a body. A package’s specification
declares the types (variables of the Record type), memory variables, constants, exceptions, cursors,
and subprograms that are available for the use.
A package’s body fully defines cursors, functions and procedures and thus implements the
specification.

Sri Ramakrishna College, Mangaluru. Page 16


PL/SQL UNIT - IV

Why use packages?


Packages offer the following advantages:
1. Packages enable the organization of commercial applications into efficient modules. Each
package is easily understood and the interfaces between packages are simple, clear and well
defined.
2. Packages allow granting of privileges efficiently
3. A package’s public variables and cursors persist for the duration of the session. Therefore all
the cursors and procedures that execute in this environment can share them
4. Packages enable the overloading of procedures and functions when required
5. Packages improve performance by loading multiple objects into memory at once. Therefore
subsequent calls to related subprograms in the package require no I/O
6. Packages promote code reuse through the use of libraries that contain stored procedures and
functions, thereby reducing redundant coding

Package specification
The package specification contains:
 Name of the package
 Names of the data types of any arguments
 This declaration is local to the database and global to the package
This means that procedure; functions, variables, constants, cursors and exceptions and other objects
declared in a package are accessible from anywhere in the package. Therefore, all the information a
package needs, to execute a stored subprogram, is contained in the package specifications itself.

Creating packages
The first step to creating a package is to create its specification. The specification declares the
objects that are contained in the body of the package. A package is created using Oracle’s SQL*Plus
interactive tool. A package can include functions and procedures. The variables declared within the
package can be accessed by any function or procedure within the package. To create a specification,
issue the CREATE PACKAGE command;

Example:
CREATE OR REPLACE PACKAGE TRANSACTION_MGMT AS
PROCEDURE PERFORM _TRANS (MACCT_NO VARCHAR2, MD VARCHAR2,
AMT NUMBER);
PROCEDURE CANCEL_FD (MFD_NO VARCHAR2);
BAL NUMBER;
P_ACCT_NO VARCHAR2 (10);
D_AMT NUMBER;
END TRANSACTION_MGMT;

Output:
Package created.
Invoking a package via the Oracle engine
When a package is invoked, the Oracle engine perform three steps to execute it:
1. Verify user access:
Confirms that the user has EXECUTE system privilege granted for the subprogram
2. Verify procedure validity:
Checks with the data dictionary to determine whether the subprogram is valid or not. If the
subprogram is invalid, it is automatically recompiled before being executed.
3. Execute:
The package subprogram is executed
To reference a package’s subprograms and objects, use dot notation

The syntax for dot notation


 PackageName.Type_Name
 PackageName.Object_Name
 PackageName.Subprogram_Name

Sri Ramakrishna College, Mangaluru. Page 17


PL/SQL UNIT - IV
In this syntax,
 PackageName is the name of the of the type that is user defined, such as record
 Type_Name is declared package
 Type_Name is the name the name of the constant or variable that is declare by the user
 Sub_program is the name of the procedure or function contained in the package body

************************

Sri Ramakrishna College, Mangaluru. Page 18

You might also like