pl/sql - drronakpanchal.files.wordpress.com · sql is a very powerful tool but it is’t a fully...
TRANSCRIPT
PL/SQL
• Introduction
Disadvantage of SQL:
1. SQL does’t have any procedural capabilities. SQL does’t
provide the programming technique of conditional checking,
looping and branching that is vital for data testing before
storage.
2. SQL statements are passed to oracle engine one at time. Each
time an SQL statements 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
manipulation of data.
SQL is a very powerful tool but it is’t a fully structured programming
language, but oracle provides a fully structured programming language with the
help of PL/SQL.
PL/SQL is super set of SQL. PL/SQL is a fully structured language that
enable developers to combine the power of SQL with the procedural statements.
Advantages of PL/SQL:
1. PL/SQL is development tool that not only supports SQL data
manipulation but also provides facilities of conditional, branching and
looping.
2. PL/SQL sends an entire block of statements to the oracle engine at one
time. This is in turn reduces network traffic.
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.
5. Via PL/SQL, all sorts of calculation can be done quickly and efficiently
without the use of the oracle engine. This improves transaction performance.
6. Applications written in PL/SQL are portable to any computer hardware and operating system, where oracle is operational.
• PL/SQL Block structure
DECLARE
Declaration of memory variables, constants, cursors, etc. in PL/SQL
BEGIN
SQL executable statements
PL/SQL executable statements
EXCEPTION
SQL or PL/SQL code to handle errors that may arise during the execution of the code block
END;
• The PL/SQL Execution Environment
PL/SQL Engine
SQL Statement
Executor
Oracle Engine
DECLARE
Procedural Statement
BEGIN
Procedural Statement
SQL statement
EXCEPTION
SQL statement
END;
• Displaying user messages on the screen
Programming tools require a method through which messages can be
displayed to the user on the VDU screen.
DBMS_OUTPUT is a package that includes a number of procedure and
functions that accumulate information in a buffer so that it can be retrieved
later. These functions can also be used to display messages to the user.
PUT_LINE put a piece of information in the package buffer followed by an
end-of-line marker. It can also be used to display message to the user.
put_line expects a single parameter of character data type.
To display message to the user the SERVEROUTPUT should be set to ON.
SERVEROUTPT is a SQL*PLUS environment parameter that displays the
information passed as a parameter to the PUT_LINE function.
Syntax:
SET SERVEROUTPUT [ON/OFF]
• Comments:
1. double hypen (--)
2. /*……………*/
• Conditional control in PL/SQL:
Syntax:
IF <condition> THEN
<action>
ELSIF <condition> THEN
<action>
ELSE
<action>
END IF;
• While Loop:
Syntax:
WHILE <condition>
LOOP
<action>
END LOOP;
• For Loop:
Syntax:
FOR variable IN [REVERSE] start….end
LOOP
<action>
END LOOP;
• The GOTO Statement:
change the flow of control within a PL/SQL block.
Syntax:
GOTO <codeblock name>;
• Transaction:
A series of one or more SQL statements that are logically related or a
series of operation performed on oracle table data is termed as a Transaction.
Oracle treat this unit as a single entity.
Oracle treats changes to table data as a two-step process. First, the
changes requested are done. Second, To make this changes permanent a
COMMIT statements has to be given at the SQL prompt, or, A ROLLBACK
statement given at the SQL prompt can be used to undo a part of or the entire
transaction.
A transaction can be closed by using either a commit or a rollback
statement. By using these statements, table data can be changed or all the
changes made to the table data undo
COMMIT:
A commit end the current transaction and makes permanent any
changes made during the transaction. All transaction lock acquired on tables
are released.
Syntax:
COMMIT;
ROLLBACK:
A rollback does exactly the opposite of commit. It ends the transaction
but undoes any changes made during the transaction. All transaction lock
acquired on tables are released.
Syntax:
ROLLBACK [WORK] [TO [SAVEPOINT] savepoint]
Where,
Work:
Is optional and is provided for ANSI compatibility.
SAVEPOINT:
Is optional and is used to rollback a partial transaction, as
far as the specified savepoint.
savepoint:
is a savepoint created during the current transaction.
Creating Savepoint:
Savepoint marks and saves the current point in the processing of
transaction.
When savepoint is used with rollback statement, parts of transaction
can be undone. An active savepoint is one that is specified since the las
COMMIT or ROLLBACK.
Syntax:
SAVEPOINT savepointname;
Rollback can be fired from the SQL prompt with or without the
SAVEPOINT clause.
Rollback Operation performed without the SAVEPOINT clause:
– Ends the transaction.
– Undoes all the changes in the current transaction.
– Erase all the savepoint in that transaction.
– Release the transaction locks.
Rollback Operation performed with the SAVEPOINT clause:
– A predetermine portion of the transaction is rolled back.
– Retains the savepoint roll back to, but loses those created after the named
savepoint.
– Release all transaction lock that were acquired since the savepoint was taken.
• Concurrency Control In Oracle:
Oracle work on a multi-user platform, it is more than likely that several
people will access data either for viewing or for manipulating from the same
tables at the same time via different SQL statements.
Tables contain valuable data on which business decisions are based.
Therefore , we need to ensure the integrity of data in a table is maintained each
time that its data is accessed.
The oracle engine has allow simultaneous access to table data without
causing damage to the data.
The technique employed by oracle engine to protect table data when
several people are accessing it is called concurrency control.
Oracle uses method called locking to implement concurrency control
when multiple users access a table to manipulate its data at the same time.
• LOCKS:
Locks are mechanism used to ensure data integrity while allowing maximum concurrent access to data.
Oracle engine automatically locks table data while executing SQL statement. This type of locking is called Implicit Locking.
Implicit Locking:
The oracle engine has fully automatic locking strategy, it has to decide on two issue:
- Type of lock to be applied
- Level of lock to be applied
--Type of Locks:
Type of lock to be placed on a resource depends on the operation being performed on that resource.
Operation on tables can be distinctly grouped into two categories:
Read Operation: SELECT statements
Write Operation: INSERT, UPDATE, DELETE statements
Read operation make no changes to data in a table and are meant only for
viewing purposes, simultaneous read operation can be performed on a table
without any danger to the table’s data. Hence, oracle engine places a ‘shared’
lock on a table when its data is being used.
On the other hand write operation can cause the change in a table data. E.g
insert, update, delete statement affect table data directly and data integrity.
Hence Oracle engine place an Exclusive lock on a table or a specific section of
table resources when data is being written to a table.
Two types of locks supported by oracle are:
– Shared locks:
Shared locks are placed on resource whenever a read operation is
performed.
Multiple shred locks can be simultaneously set on a resource.
– Exclusive locks:
Exclusive locks are placed on resources whenever a write operation is
performed.
Only on exclusive lock can be placed on a resource at a time, e.g the first
user who acquires an exclusive lock will continue to have the sole
ownership of the resource, and no other user can acquire an exclusive lock
on that resource.
Data being changed can not read.
-- Levels of locks:
Oracle provides the following three levels of locking:
– Row Level
– Page Level
– Table Level
The oracle engine decides on the level to be used by the presence
or absence of a where condition in the SQL sentence.
-- If the where clause evaluates to only one row in the table, a
row level lock is used.
-- If the where clause evaluates to a set of data, a page level lock
is used.
-- If there is no WHERE clause, a table level lock is used.
Explicit Locking:
The technique of lock taken on a table or its resources by a user is called
explicit locking.
User can lock tables they own or any tables on which they have been
granted table privileges ( such as select, insert, update, delete)
Oracle provides facilities by which the default locking strategy can be
overridden. Table(s) or Row(s) can be explicitly locked by using either the
select…..for update statement, or lock table statement.
The Select….For Update statement:
It is used for acquiring exclusive row level locks in anticipating of
performing updates on records. This clause is generally used to signal the oracle
engine that data currently being used needs to be updated. It is often followed
by one or more update statements with a where clause.
Example:
Client A fires the following select statement
Client A> SELECT * FROM sale_order
WHERE order_no=‘O00001’ FOR UPDATE
When the above select statement is fired, the oracle engine locks the record O00001. This lock is released when a commit or rollbacl is fired by client A.
If Client B fires a select statement which points to record O00001, which has already been locked by Client A.
Client B> SELECT * FROM sale_order
WHERE order_no=‘O00001’ FOR UPDATE
The oracle engine will ensure that client B’s SQL statement wits for the lock to be released on sales_order by a commit or rollback statement fired by Client A forever.
In Order to avoid unnecessary waiting time, a NOWAIT optin can be used to inform the oracle engine to terminate the SQL statement if the record has already been locked. If this happen the oracle engine terminates the running DML and comes up with a message indicating that the resource is busy.
Client B> SELECT * FROM sale_order
WHERE order_no=‘O00001’ FOR UPDATE NOWAIT;
Since Client A has already locked the record O00001 when client B tries to
acquire a shared lock on the same record the oracle engine displays the
following message:
SQL>00054: resource busy and acquire with nowait specified.
The select….. For update cannot be used with the following:
– Distinct and the group by clause
– Set operators and group functions.
Using Lock table statement:
To manually override oracle’s default locking strategy by creating a data
lock in a specific mode.
Syntax:
LOCK TABLE tablename [,tablename]…….
IN {ROW SHARE|ROW EXCLUSIVE|SHARE
UPDATE|SHARE|SHARE ROW EXCLUSIVE|EXCLUSIVE}
{NOWAIT}
where,
tablename: indicates the name of tables, views to be locked. In case of
views, the lock is placed on underlying tables.
IN :decide what other locks on the same resource can exist
simultaneously. For example, if there is exclusive lock on the table
no user can update rows in the table. It can have any of the following
values:
Exclusive: They allow query on the locked resource but prohibit any other
activity.
Share: It allows queries but prohibits updates to a table.
Row Exclusive: Row exclusive locks are the same as row share locks, also
prohibit locking in shared mode. These locks are acquired
when updating, inserting, or deleting.
Share Row Exclusive: They are used to look at a whole table, to selective
updates and to allow other users to look at rows in
the table but not lock the table in share mode or to
update rows.
NOWAIT: Indicates that the oracle engine should immediately return to
the user with a message, if the resources are busy. If omitted,
the oracle engine will wait till resources are available forever.
For Example,
LOCK TABLE emp
IN exclusive mode
NOWAIT;
• Processing A PL/SQL Block
Whenever an SQL statements 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 completed.
A PL/SQL block can be run in one of he following 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 interval to
process table data. A technique that oracle provides for manipulating table data in
batch processing mode is the use of cursors.
• 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 store in the cursor is called as Active Data Set. 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 is determined by the oracle engine’s built in memory
management capabilities and the amount of RAM available.
When the cursor is loaded with multiple rows via query the oracle engine
opens and maintains a row pointer. Depending on user requests to view data
the row pointer will be relocated within the cursor’s active data set.
Additionally oracle also maintain multiple cursor variables. The values held in
these variables indicate the status of the processing being done by the cursor.
Types Of Cursor:
Cursors are classified depending on which they are opened. If the oracle
engine for its internal processing has opened a cursor they are known as Implicit
Cursors. A user can also open a cursor for processing data as required, such a
user-defined cursors are known as Explicit Cursor.
When oracle engine creates an implicit or explicit cursor, cursor control
variables are also created to control the execution of the cursor. Whenever
cursor is opened and used, the oracle engine creates 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 and they are:
Attribute Name Description
%ISOPEN Return TRUE if cursor is open. FALSE otherwise.
SQL%ISOPEN attribute of an implicit cursor
cannot be referenced outside of its SQL statement.
As a result, SQL%ISOPEN always evaluates to
FALSE.
%FOUND Return TRUE if records fetched successfully
otherwise FALSE. Syntax: SQL%FOUND
%NOTFOUND Return TRUE if record was not fetched successfully.
otherwise FALSE. Syntax: SQL%NOTFOUND
%ROWCOUNT Returns number of records processed from the
cursor. Syntax: 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 a SQL query in the declared
section of the PL/SQL block and used within the executable section.
Thus, a cursor is created and used is know as a Explicit Cursor.
Explicit Cursor Management:
The step involved in using an explicit cursor and manipulating data in its
active set are:
– Declared a cursor mapped to a SQL select statement that retrieves data for
processing.
– Open the cursor
– Fetch data from the cursor one row at a time into memory variables.
– Process the data held in 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 the declarative part of a PL/SQL block.
Syntax:
CURSOR cursorname IS
SQL Select statement;
When a cursor is declared, the oracle engine is informed that a cursor of
the said name needs to be opened. The declaration is only an intimation. There
is no memory allocation at this point in time.
The three command used to control the cursor subsequently are open,
fetch and close.
The Functionality of Open, Fetch, and Close:
Initialization of a cursor takes place via the open statement, This define a
private SQL area named after the cursor name, and execute the query and
create a active data set that contain all the rows, which meet the query search
criteria.
Syntax:
OPEN cursorname
A fetch statement then moves the data held in the active data set into
memory variable data held in the memory variables can be processed as desired.
The fetch statement is placed inside the loop…..end loop construct, which
cause the data to be fetch one row at a time and processed until all the rows in
the active data set are processed.
Syntax:
FECTH cursorname INTO varable1, variable2…..;
Note:
There must be memory variable for each column value of the active data
set. Data types must match. These variable will be declared in the DECLARED
section of the PL/SQL block.
After the fetch loop exist, the cursor must be closed with the close statement.
This will release the memory occupied by the cursor and its active data set.
Syntax:
CLOSE cursorname;
Explicit Cursor Attributes:
Similar to the cursor attribute in case of implicit cursors, for attributes are
associated with explicit cursor.
• 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.
Syntax:
FOR memory variable IN cursorname
Here, the verb FOR automatically creates the memory variable of the
%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 execute once. This goes on
until all the rows of the cursor have been loaded into memory variable. After
this the loop stop.
A cursor for loop automatically does the following :
– Implicitly declares its loop index as a %rowtype record.
– Open a cursor
– Fetch a row from the cursor for each loop iteration.
– Closes the cursor when all rows have been processed.
• Parameterized Cursors:
Till now all the cursor that have been declared and used fetch a
predetermine set of records. Records which satisfy condition of the select
statement mapped to the cursor, means the criteria on which the active data set
is determined is hard coded and never changes.
commercial application 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 the need.
oracle recognized this and permits the creation of a parameterized cursor,
hence the contents of the opened cursor will constantly change depending
upon a value passed.
since the cursor accepts values or parameters it is called as a
parameterized cursor. The parameters can be either a constant or a variable.
Declaring a Parameterized Cursor:
Syntax:
CURSOR cursor_name(variable_name datatpe) IS
<SELECT statement…..>
Opening a Parameterized Cursor:
Syntax:
OPEN cursor_name(value/variable/expression)
• Exception Handling:
While executing the SQL sentence anything can go wrong and the SQL
sentence fail the oracle engine is the first to recognize this as an Exception
Condition.
The Oracle engine immediately tries to handle the exception condition and
resolve it. This is done by raising a built-in Exception Handler.
Exception handler is nothing but a code of block in memory that will
attempt to resolve the current exception condition. These exception handler are
identified not by names but by four integer preceded by hyphen e.g -1414.
These exception handler names are actually a set of negative signed
integers. Each exception handler, irrespective of how it is identified (by name
or number) has code attached that will attempt to resolve an exception
condition. By this way oracle’s default exception-handling work.
We can handle our exception in our block with the help of defining
explicit exception in block, at that time oracle’s default exception handling
code will be override and oracle’s default exception handling code is not
executed but the code block that takes care of the exception condition in the
exception section of the block is executed.
Oracle engine’s exception handler must establish whether to execute its
own exception handling code or whether it has to execute user defined
exception handling code.
How oracle engine handle exception
As soon as the oracle engine invokes an exception handler the exception
handler goes back to the PL/SQL block from which the exception condition
was raised.
The exception handler scans the PL//SQL block for the existence of an
exception section within the PL/SQL block. If an exception section within the
PL/SQL block exists the exception handler scan the first word, after the action
word when, within the exception section.
If the first word after the action word when is the exception handler’s
name then the exception handler executes the code contained in the then
section of the construct as follows:
Exception
When {Exception Name} Then
{User defined action to be carried out}
Oracle’s Named Exception Handlers
The oracle engine has a set of pre-defined oracle error handlers called
Named Exceptions. These error handlers are referenced by their name. The
following are some of the pre-defined oracle named exception handlers:
1. DUP_VAL_ON_INDEX:
Raised when an insert or update attempts to create two rows with
duplicate values in columns constrained by a unique index.
2. LOGIN_DENIED:
Raised when an invalid username/password was used to log onto
oracle.
3.NO_DATA_FOUND:
Raised when a select statement returns zero rows.
4.NOT_LOGGED_ON:
Raised when PL/SQL issues an oracle call without being
logged onto oracle.
5.PROGRAM_ERROR:
Raised when PL/SQL has an internal problem.
6.TIMEOUT_ON_RESOURCE:
Raised when oracle has been waiting to access a resource
beyond the user defined timeout limit.
7.TOO_MANY_ROWS:
Raised when a select statement returns more than one row.
8.VALUE_ERROR:
Raised when the data type or data size is invalid.
9.OTHERS:
Stands for all other exception not explicitly named.
User-Named Exception Handlers:
The technique that is used is to bind a numbered exception
handler to a name using ‘Pragma Exception_init()’, This binding is done in
Declare Section.
All object declare section of a PL/SQL block are not created
until actually required within the PL/SQL block. However, the binding of a
numbered exception handler to a name must be done exactly when declared
not when the exception handler is invoked due to an exception condition.
Syntax:
DECLARE
exception_name EXCEPTION;
PRAGMA EXCEPTION_INIT(excepion_name,
error_code_no);
The Pragma action word is a call to a pre-compiler, which immediately
binds the numbered exception handler to a name when encountered.
The function Exception_init() takes two parameters the first is the user
defined exception name the second is the oracle engine’s exception number.
User Defined Exception Handling For Business Rule
Validation:
To trap business rules being violated the technique of raising user-
defined exception and then handling them is used.
All the business rule exception are completely transparent to the oracle
engine and hence the skill of translating a business rule into appropriate
PL/SQL user-defined exception handling code is vital to a programmer.
User-defined error condition 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 exists, the call to the user defined
exception is made using a RAISE statement. The exception once raised is
then handled in the exception handling section of the PL/SQL code block.
Syntax:
DECLARE
<Exceptionname> Exception
BEGIN
SQL sentence;
IF <condition> THEN
RAISE <Exceptionname>;
END IF;
EXCEPTION
WHEN <Exceptionname> THEN
{User defined action to be taken};
END;