UNIT VI PL SQL
UNIT VI PL SQL
languages. It was developed by Oracle Corporation in the early 90's to enhance the
capabilities of SQL.
Features of PL/SQL
Advantages of PL/SQL
1. SQL is the standard database language and PL/SQL is strongly integrated with
SQL. PL/SQL supports both static and dynamic SQL. Static SQL supports DML
operations and transaction control from PL/SQL block. In Dynamic SQL, SQL
allows embedding DDL statements in PL/SQL blocks.
2. PL/SQL allows sending an entire block of statements to the database at one time.
This reduces network traffic and provides high performance for the applications.
3. PL/SQL gives high productivity to programmers as it can query, transform, and
update data in a database.
4. PL/SQL saves time on design and debugging by strong features, such as
exception handling, encapsulation, data hiding, and object-oriented data types.
5. Applications written in PL/SQL are fully portable.
6. PL/SQL provides a high-security level.
7. PL/SQL provides access to predefined SQL packages.
8. PL/SQL provides support for Object-Oriented Programming.
9. PL/SQL provides support for developing Web Applications and Server Pages.
PL/SQL programs are divided and written in logical blocks of code. Each block
consists of three sub-parts −
Declarations
1
This section starts with the keyword DECLARE. It is an optional section and defines all
variables, cursors, subprograms, and other elements to be used in the program.
Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a mandatory
2
section. It consists of the executable PL/SQL statements of the program. It should have at
least one executable line of code, which may be just a NULL command to indicate that
nothing should be executed.
Exception Handling
3
This section starts with the keyword EXCEPTION. This optional section
contains exception(s) that handle errors in the program.
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested
within other PL/SQL blocks using BEGIN and END. Following is the basic
structure of a PL/SQL block −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
Example:
SQL> DECLARE
3 BEGIN
4 dbms_output.put_line(message);
5 END ;
6 /
The end; line signals the end of the PL/SQL block. To run the code from the SQL
command line, you may need to type / at the beginning of the first blank line after the
last line of the code. When the above code is executed at the SQL prompt, it produces
the following result −
Hello, World!
Delimiter Description
% Attribute indicator
. Component selector
, Item separator
= Relational operator
:= Assignment operator
|| Concatenation operator
** Exponentiation operator
.. Range operator
Program comments are explanatory statements that can be included in the PL/SQL
code that you write and helps anyone reading its source code. All programming
languages allow some form of comments.
The PL/SQL supports single-line and multi-line comments. All characters available
inside any comment are ignored by the PL/SQL compiler. The PL/SQL single-line
comments start with the delimiter -- (double hyphen) and multi-line comments are
enclosed by /* and */.
DECLARE
-- variable declaration
BEGIN
/*
*/
dbms_output.put_line(message);
END;
When the above code is executed at the SQL prompt, it produces the following result
−
Hello World!
PL/SQL block
Function
Package
Package body
Procedure
Trigger
Parameter Modes in PL/SQL Subprograms
The following table lists out the parameter modes in PL/SQL subprograms −
IN
OUT
2 An OUT parameter returns a value to the calling program. Inside the subprogram, an OUT
parameter acts like a variable. You can change its value and reference the value after
assigning it. The actual parameter must be variable and it is passed by value.
IN OUT
An IN OUT parameter passes an initial value to a subprogram and returns an updated value
to the caller. It can be assigned a value and the value can be read.
3
The actual parameter corresponding to an IN OUT formal parameter must be a variable, not
a constant or an expression. Formal parameter must be assigned a value. Actual parameter
is passed by value.
Write a PL SQL programe which finds the minimum of two values. Here, the
procedure takes two numbers using the IN mode and returns their minimum using the
OUT parameters.
DECLARE
a number;
b number;
c number;
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
END;
When the above code is executed at the SQL prompt, it produces the following result
−
a number;
b number;
c number;
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);
END;
When the above code is executed at the SQL prompt, it produces the following result
−
Maximum of (23,45): 45
PL/SQL procedure successfully completed.
Write a PL SQL programe which calculates the factorial of a given number by calling
itself recursively
DECLARE
num number;
factorial number;
RETURN number
IS
f number;
BEGIN
IF x=0 THEN
f := 1;
ELSE
f := x * fact(x-1);
END IF;
RETURN f;
END;
BEGIN
num:= 6;
factorial := fact(num);
END;
/
When the above code is executed at the SQL prompt, it produces the following result
−
Factorial 6 is 720
PL/SQL - Cursors
Oracle creates a memory area, known as the context area, for processing an SQL
statement, which contains all the information needed for processing the statement;
for example, the number of rows processed, etc.
A cursor is a pointer to this context area. PL/SQL controls the context area through
a cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set
of rows the cursor holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and
process the rows returned by the SQL statement, one at a time. There are two types
of cursors −
Implicit cursors
Explicit cursors
Implicit Cursors
%FOUND
1
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows
or a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.
%NOTFOUND
%ISOPEN
3
Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
%ROWCOUNT
4
Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or
returned by a SELECT INTO statement.
The following program will update the table and increase the amount of each order
by 500 and use the SQL%ROWCOUNT attribute to determine the number of rows
affected −
When the above code is executed at the SQL prompt, it produces the following result
−
5 orders selected
PL/SQL procedure successfully completed.
If you check the records in orders table, you will find that the rows have been
updated
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over
the context area. An explicit cursor should be defined in the declaration section of
the PL/SQL Block. It is created on a SELECT Statement which returns more than
one row.
Declaring the cursor defines the cursor with a name and the associated SELECT
statement. For example −
CURSOR c_customers IS
OPEN c_customers;
Fetching the cursor involves accessing one row at a time. For example, we will fetch
rows from the above-opened cursor as follows −
Closing the cursor means releasing the allocated memory. For example, we will close
the above-opened cursor as follows −
CLOSE c_customers;
Example
Create procedure:
Execute the following program to retrieve the customer name and address.
1. DECLARE
2. c_id customers.id%type;
3. c_name customers.name%type;
4. c_addr customers.address%type;
5. CURSOR c_customers is
6. SELECT id, name, address FROM customers;
7. BEGIN
8. OPEN c_customers;
9. LOOP
10. FETCH c_customers into c_id, c_name, c_addr;
11. EXIT WHEN c_customers%notfound;
12. dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
13. END LOOP;
14. CLOSE c_customers;
15. END;
16. /
PL/SQL - Exceptions
An exception is an error condition during a program execution. PL/SQL supports
programmers to catch such conditions using EXCEPTION block in the program and
an appropriate action is taken against the error condition.
System-defined exceptions
User-defined exceptions
The general syntax for exception handling is as follows. Here you can list down as
many exceptions as you can handle. The default exception will be handled
using WHEN others THEN −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
exception1-handling-statements
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
exception3-handling-statements
END;
Example
Let us write a code to illustrate the concept. We will be using the CUSTOMERS
DECLARE
c_id customers.id%type := 8;
c_name customers.Name%type;
c_addr customers.address%type;
BEGIN
FROM customers
WHERE id = c_id;
EXCEPTION
dbms_output.put_line('Error!');
END; /
When the above code is executed at the SQL prompt, it produces the following result
−
No such customer!
The above program displays the name and address of a customer whose ID is given.
Since there is no customer with ID value 8 in our database, the program raises the
run-time exception NO_DATA_FOUND, which is captured in the EXCEPTION
block.
Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any
internal database error, but exceptions can be raised explicitly by the programmer by
using the command RAISE. Following is the simple syntax for raising an exception
−
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
statement;
END;
You can use the above syntax in raising the Oracle standard exception or any user-
defined exception. In the next section, we will give you an example on raising a user-
defined exception. You can raise the Oracle standard exceptions in a similar way.
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your
program. A user-defined exception must be declared and then raised explicitly, using
either a RAISE statement or the
procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
DECLARE
my-exception EXCEPTION;
Example
The following example illustrates the concept. This program asks for a customer ID,
when the user enters an invalid ID, the exception invalid_id is raised.
DECLARE
c_name customerS.Name%type;
c_addr customers.address%type;
ex_invalid_id EXCEPTION;
BEGIN
RAISE ex_invalid_id;
ELSE
FROM customers
WHERE id = c_id;
END IF;
EXCEPTION
dbms_output.put_line('Error!'); END; /
When the above code is executed at the SQL prompt, it produces the following result
−
PL/SQL - Triggers
Triggers are stored programs, which are automatically executed or fired
when some events occur. Triggers are, in fact, written to be executed in
response to any of the following events −
Benefits of Triggers
Auditing
Creating Triggers
The syntax for creating a trigger is −
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements END;
Where,
CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces
an existing trigger with the trigger_name.
{BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will
be executed. The INSTEAD OF clause is used for creating trigger on a
view.
{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML
operation.
[OF col_name] − This specifies the column name that will be updated.
[ON table_name] − This specifies the name of the table associated with
the trigger.
[REFERENCING OLD AS o NEW AS n] − This allows you to refer new
and old values for various DML statements, such as INSERT, UPDATE,
and DELETE.
[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will
be executed for each row being affected. Otherwise the trigger will
execute just once when the SQL statement is executed, which is called a
table level trigger.
WHEN (condition) − This provides a condition for rows for which the
trigger would fire. This clause is valid only for row-level triggers.
Example
To start with, we will be using the ORDERS table we had created and used in
the previous chapters −
The following program creates a row-level trigger for the customers table
that would fire for INSERT or UPDATE or DELETE operations performed on
the ORDERS table. This trigger will display the salary difference between the
old values and new values −
DECLARE
amt_diff number;
BEGIN
END;
Triggering a Trigger
Let us perform some DML operations on the ORDERS table. Here is one
INSERT statement, which will create a new record in the table −
INSERT INTO ORDERS (ONUM,AMT,ODATE,CNUM,SNUM )
VALUES (309, 1600, '22-FEB-21', 201,101);