0% found this document useful (0 votes)
47 views25 pages

UNIT VI PL SQL

PL/SQL is a programming language developed by Oracle Corporation to enhance the capabilities of SQL. It allows developers to write programs that combine SQL statements with procedural code. PL/SQL offers features like error checking, data types, programming structures, functions and procedures, object-oriented programming, and support for web and server-side applications. It provides blocks of reusable code through procedures, functions, packages and triggers.

Uploaded by

23mca006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views25 pages

UNIT VI PL SQL

PL/SQL is a programming language developed by Oracle Corporation to enhance the capabilities of SQL. It allows developers to write programs that combine SQL statements with procedural code. PL/SQL offers features like error checking, data types, programming structures, functions and procedures, object-oriented programming, and support for web and server-side applications. It provides blocks of reusable code through procedures, functions, packages and triggers.

Uploaded by

23mca006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

PL/SQL is a combination of SQL along with the procedural features of programming

languages. It was developed by Oracle Corporation in the early 90's to enhance the
capabilities of SQL.

Features of PL/SQL

PL/SQL has the following features −

 PL/SQL is tightly integrated with SQL.

 It offers extensive error checking.

 It offers numerous data types.

 It offers a variety of programming structures.

 It supports structured programming through functions and procedures.

 It supports object-oriented programming.

 It supports the development of web applications and server pages.

Advantages of PL/SQL

PL/SQL has the following advantages −

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 −

S.N Sections & Description


o

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> set serveroutput on;

SQL> DECLARE

2 message varchar2(20):= 'Hello, World!';

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!

PL/SQL procedure successfully completed.

The PL/SQL Identifiers

PL/SQL identifiers are constants, variables, exceptions, procedures, cursors, and


reserved words. The identifiers consist of a letter optionally followed by more letters,
numerals, dollar signs, underscores, and number signs and should not exceed 30
characters.
By default, identifiers are not case-sensitive. So you can
use integer or INTEGER to represent a numeric value. You cannot use a reserved
keyword as an identifier.

The PL/SQL Delimiters

A delimiter is a symbol with a special meaning. Following is the list of delimiters in


PL/SQL −

Delimiter Description

+, -, *, / Addition, subtraction/negation, multiplication, division

% Attribute indicator

' Character string delimiter

. Component selector

(,) Expression or list delimiter

: Host variable indicator

, Item separator

" Quoted identifier delimiter

= Relational operator

@ Remote access indicator


; Statement terminator

:= Assignment operator

=> Association operator

|| Concatenation operator

** Exponentiation operator

<<, >> Label delimiter (begin and end)

/*, */ Multi-line comment delimiter (begin and end)

-- Single-line comment indicator

.. Range operator

<, >, <=, >= Relational operators

<>, '=, ~=, ^= Different versions of NOT EQUAL

The PL/SQL Comments

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

message varchar2(20):= 'Hello, World!';

BEGIN

/*

* PL/SQL executable statement(s)

*/

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 procedure successfully completed.

PL/SQL Program Units

A PL/SQL unit is any one of the following −

 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 −

S.N Parameter Mode & Description


o

IN

An IN parameter lets you pass a value to the subprogram. It is a read-only parameter.


Inside the subprogram, an IN parameter acts like a constant. It cannot be assigned a value.
1
You can pass a constant, literal, initialized variable, or expression as an IN parameter. You
can also initialize it to a default value; however, in that case, it is omitted from the
subprogram call. It is the default mode of parameter passing. Parameters are passed by
reference.

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.

IN & OUT Mode Example 1

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;

PROCEDURE findMin(x IN number, y IN number, z OUT number) IS

BEGIN

IF x < y THEN

z:= x;

ELSE

z:= y;

END IF;

END;

BEGIN

a:= 23;

b:= 45;

findMin(a, b, c);

dbms_output.put_line(' Minimum of (23, 45) : ' || c);

END;

When the above code is executed at the SQL prompt, it produces the following result

Minimum of (23, 45) : 23

PL/SQL procedure successfully completed.

Write a PL SQL programe which demonstrates Declaring, Defining, and Invoking a


Simple PL/SQL Function that computes and returns the maximum of two values.
DECLARE

a number;

b number;

c number;

FUNCTION findMax(x IN number, y IN 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);

dbms_output.put_line(' Maximum of (23,45): ' || c);

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;

FUNCTION fact(x 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);

dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);

END;

/
When the above code is executed at the SQL prompt, it produces the following result

Factorial 6 is 720

PL/SQL procedure successfully completed.

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

Implicit cursors are automatically created by Oracle whenever an SQL statement is


executed, when there is no explicit cursor for the statement. Programmers cannot
control the implicit cursors and the information in them.

Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an


implicit cursor is associated with this statement. For INSERT operations, the cursor
holds the data that needs to be inserted. For UPDATE and DELETE operations, the
cursor identifies the rows that would be affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor,
which always has attributes such as %FOUND, %ISOPEN, %NOTFOUND,
and %ROWCOUNT. The SQL cursor has additional
attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for
use with the FORALL statement. The following table provides the description of the
most used attributes −

S.N Attribute & Description


o

%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

2 The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE


statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it
returns FALSE.

%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.

Any SQL cursor attribute will be accessed as sql%attribute_name as shown below


in the example.

Example (Implicit Cursor)


We will be using the ORDERS table we had created and used in the previous
chapters.

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.

The syntax for creating an explicit cursor is −

CURSOR cursor_name IS select_statement;

Working with an explicit cursor includes the following steps −

 Declaring the cursor for initializing the memory

 Opening the cursor for allocating the memory

 Fetching the cursor for retrieving the data

 Closing the cursor to release the allocated memory

Declaring the Cursor

Declaring the cursor defines the cursor with a name and the associated SELECT
statement. For example −

CURSOR c_customers IS

SELECT id, name, address FROM customers;

Opening the Cursor


Opening the cursor allocates the memory for the cursor and makes it ready for
fetching the rows returned by the SQL statement into it. For example, we will open
the above defined cursor as follows −

OPEN c_customers;

Fetching the Cursor

Fetching the cursor involves accessing one row at a time. For example, we will fetch
rows from the above-opened cursor as follows −

FETCH c_customers INTO c_id, c_name, c_addr;

Closing the Cursor

Closing the cursor means releasing the allocated memory. For example, we will close
the above-opened cursor as follows −

CLOSE c_customers;

Example

Following is a complete example to illustrate the concepts of explicit cursors:


When the above code is executed at the SQL prompt, it produces the above result.

Example of explicit cursor:

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.

There are two types of exceptions −

 System-defined exceptions

 User-defined exceptions

Syntax for Exception Handling

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

<exception handling goes here >

WHEN exception1 THEN

exception1-handling-statements

WHEN exception2 THEN

exception2-handling-statements
WHEN exception3 THEN

exception3-handling-statements

........

WHEN others THEN

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

SELECT name, address INTO c_name, c_addr

FROM customers

WHERE id = c_id;

DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);

DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);

EXCEPTION

WHEN no_data_found THEN

dbms_output.put_line('No such customer!');

WHEN others THEN

dbms_output.put_line('Error!');

END; /
When the above code is executed at the SQL prompt, it produces the following result

No such customer!

PL/SQL procedure successfully completed.

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

WHEN exception_name THEN

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.

The syntax for declaring an exception is −

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_id customers.id%type := &cc_id;

c_name customerS.Name%type;

c_addr customers.address%type;

-- user defined exception

ex_invalid_id EXCEPTION;

BEGIN

IF c_id <= 0 THEN

RAISE ex_invalid_id;

ELSE

SELECT name, address INTO c_name, c_addr

FROM customers

WHERE id = c_id;

DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);


DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);

END IF;

EXCEPTION

WHEN ex_invalid_id THEN

dbms_output.put_line('ID must be greater than zero!');

WHEN no_data_found THEN

dbms_output.put_line('No such customer!');

WHEN others THEN

dbms_output.put_line('Error!'); END; /

When the above code is executed at the SQL prompt, it produces the following result

Enter value for cc_id: -6 (let's enter a value -6)

old 2: c_id customers.id%type := &cc_id;

new 2: c_id customers.id%type := -6;

ID must be greater than zero!

PL/SQL procedure successfully completed.

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 −

 A database manipulation (DML) statement (DELETE, INSERT, or


UPDATE)
 A database definition (DDL) statement (CREATE, ALTER, or DROP).
 A database operation (SERVERERROR, LOGON, LOGOFF,
STARTUP, or SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which
the event is associated.

Benefits of Triggers

Triggers can be written for the following purposes −

 Generating some derived column values automatically

 Enforcing referential integrity

 Event logging and storing information on table access

 Auditing

 Synchronous replication of tables

 Imposing security authorizations

 Preventing invalid transactions

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 −

CREATE OR REPLACE TRIGGER display_salary_changes

BEFORE DELETE OR INSERT OR UPDATE ON orders

FOR EACH ROW

WHEN (NEW.onum > 305)

DECLARE

amt_diff number;

BEGIN

amt_diff := :NEW.amt - :OLD.amt;

dbms_output.put_line('Old salary: ' || :OLD.amt);

dbms_output.put_line('New salary: ' || :NEW.amt);


dbms_output.put_line('Salary difference: ' || amt_diff);

END;

The following points need to be considered here −


 OLD and NEW references are not available for table-level triggers, rather
you can use them for record-level triggers.
 If you want to query the table in the same trigger, then you should use the
AFTER keyword, because triggers can query the table or change it again
only after the initial changes are applied and the table is back in a
consistent state.
 The above trigger has been written in such a way that it will fire before
any DELETE or INSERT or UPDATE operation on the table, but you can
write your trigger on a single or multiple operations, for example BEFORE
DELETE, which will fire whenever a record will be deleted using the
DELETE operation on the table.

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);

You might also like