Unit4 PLSQL
Unit4 PLSQL
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.
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.
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.
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.
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.
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:-
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;
/
PL/SQL TRANSACTIONS
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.
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.
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.
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.
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.
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.
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;
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;
%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.
Since the cursor accepts user-defined value into its parameters, thus changing the result set a
extracted, it is called Parameterized 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.
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 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
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.
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.
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.
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.
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
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.
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.
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;
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;
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.
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
************************