You are on page 1of 22

PL/SQL

Introduction to PL/SQL :

PL/SQL stands for Procedural Language SQL. PL/SQL extends SQL by adding
control structures found in other procedural language.
PL/SQL is unique as it combines the flexibility of SQL with the power and
configurability of a third generation language. The procedural constructs and
database access are present in PL/SQL.
PL/SQL can be used in the Oracle relational database in the Oracle
server and in client side application development tools.

Disadvantages of SQL:-

 SQL does not provide the programming techniques of conditional checking,


Looping & Branching that is vital for data testing before storage.

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

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

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.

Advantages of PL/SQL:-
 PL/SQL is a development tool that not only supports SQL data manipulation but
also provides facilities of conditional checking Branching and Looping

 PL/SQL sends an entire block of statements to the Oracle engine at one time.
The communication between the program block and the Oracle engine reduces
considerably which in turn reduces network traffic. Oracle engine gets the SQL
statements as a single block, and hence it processes this code much faster than if
it got the code one sentence at a time. Result is that there is definite
improvement in the performance time of the Oracle engine

 PL/SQL displays user-friendly messages, when errors are encountered

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

 Applications written in PL/SQL are portable to any computer hardware and


operating system, where Oracle is operational.
Architecture of PL/SQL:

ORACLE Server

Host program
Or
Oracle Tool
PL/SQL Engine
Procedural
PL/SQL Statement
PL/SQL Procedural
Block Executor
Engine

SQL Statement Executor

PL/SQL Block:-

A PL/SQL Block has a definite structure. The minimum sections of a PL/SQL block
are

 The Declare Section.

 The master Begin & End Section that contains the Exception Section.
DECLARE

Declarations of memory variables, constants & cursors.

BEGIN

SQL executable statements


PL/SQL executable statements

EXCEPTION

SQL or PL/SQL code to handle errors.

END;

Data Types
Number ( )

Char ( ), varchar ( ),varchar2 ( )

Date

Boolean

Attributes:
Attributes allow us to refer to data types and objects from the database.
PL/SQL variables and constants can have attributes. The following are the types of
attributes supported by PL/SQL.

%type
%rowtype
%type: %type attribute is used when declaring variables that refer to the database
columns.

Eg: Declare
em emp.empno%type ;

The advantages of using %type is


We need not know the exact data type of the column em.
If the database definition of ‘empno’ changes, then, the data type of ‘em’
changes accordingly at run time.

%rowtype: %rowtype attribute provides a record type that represents a row in a


table.
The record can store an entire row of data selected from the table or fetched by a
cursor.

Data types as the columns in the emp table.

Eg: declare
em1 emp%rowtype;

In the above example, em1 stores a row selected from the emp table.
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.

Assigning Values to variables :


Using the assignment operator :=

CONSTANTS

Declaring a constant is similar to declaring a variable except that u have to add


the keyword “constant”

Syntax:-
<var> constant number;
ex: x constant number :=10;

Displaying user messages on the screen

DBMS_OUTPUT .PUT_LINE

To display messages to the user the SERVEROUTPUT should be set to ON.

Syntax:-
SET SERVEROUTPUT [ON/OFF]

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.
PUT_LINE : Put a piece of information in the package buffer followed by an
end-of-line marker. It can also used to display message to the user.

Comments:-

A comment can have two forms;

The comment begins with a double Hyphen (--).

The comment line begins with a Slash followed by an Asterisk (/*) till the
occurrence of an Asterisk followed by a Slash (*/)

Conditional Control in PL/SQL

Syntax:-

IF<Condition> THEN

<Action>

ELSIF<condition>THEN

<Action>

ELSE

<Action>

END IF;

Program Name : big.sql


Step 1 : First type ed big.sql at SQL Prompt and then we get the notepad opened
with file name as big.sql. If the file is already existing then it will open the existing file
or else it will create a new file. Then type the following program and save and exit
from the editor. And you will return to SQL Prompt. Then Step 2 continues.

declare

a number;

b number;

begin

a:=&a;

b:=&b;

if (a>b) then

dbms_output.put_line(‘a is big’);

else

dbms_output.put_line(‘b is big’);

end if;

end;

Step 2 : Execution

We can execute the Sql file by using the RUN Command or @ Symbol. If we
have stored the sql file in default directory then we can directly specify the file name.

SQL> @ big.sql (or) SQL> RUN big.sql

If we have stored the SQL file in our own defined directory (e.g. c:\bhavans)
then we should specify the complete path along with the command.

SQL> @ c:\bhavans\big.sql (or) SQL> RUN c:\bhavans\


big.sql
PL/SQL procedure successfully completed.

Iterative Controls

1 . While loop
Syntax:
While <condition> loop
---------------
---------------
End loop;

SQL> ed c:\bhavans\natural.sql

natural.sql
declare

i number;

n number;

begin

i:=0;

n:=&n;

while (i<n) loop

i:=i+1;

dbms_output.put_line(i);

end loop;

end;

/
Output & Execution :

SQL> @ c:\bhavans\natural.sql
Enter value for n: 4
old 6: n:=&n;
new 6: n:=4
1
2
3
4
PL/SQL procedure successfully completed.

2 .For loop

Syntax:
FOR <variable> IN [REVERSE] start..end loop
----------------
END LOOP;

Power.sql

SQL> ed c:\bhavans\power.sql
declare
power number;
b number:=&b;
e number:=&e;
i number;
begin
power:=1;
for i in 1..e loop
power:=power*b;
end loop;
dbms_output.put_line(‘The Power of the Given Expression is ||power);
end;
/

3. Loop

Syntax:

LOOP

-----------

-----------

EXIT WHEN <condition>

END LOOP;

EXCEPTION HANDLING :

In PL/SQL a warning or error condition is called an


exception. Exceptions are designed for run time error handling, rather than compile
time error handling. Exceptions and exception handlers are the method by which the
program reacts and deals with run time errors.

Advantages of Exceptions :

Without exception handling every time you issue a command,


you must check for execution errors.
If you neglect to code a check ,the error goes undetected and is
likely to cause other, seemingly unrelated errors.

With exceptions you can handle errors conveniently without


the need to code multiple checks, as follows.

Exceptions are classified into two types they are

1). Pre-defined Exceptions

2). User-defined Exceptions.

1). Predefined Exceptions :

An internal exception is raised implicitly whenever your PL/SQL


program violates an oracle rule or exceeds a system-dependent limit . Every oracle
error has a number, but exceptions must be handled by name. So PL/SQL predefines
some common Oracle errors as exceptions.

PREDEFINED EXPLANATION
EXCEPTION
No_data_found This exception is raised when select statement returns no
rows.
Cursor_already_open This exception is raised when we try to open a cursor
which is already opened.

Dup_val_on_index This exception is raised when we insert duplicate values in a


column, which is defined as unique index.
Program_error This exception is raised if PL/SQL has an internal problem.
Zero_divide This exception is raised when we try to divide a number by
zero.
Invalid_cursor This exception is raised when we violate cursor operation.
For example, when we try to close a cursor which is not
opened.
Login_denied This exception is raised when we try to enter oracle using
invalid username/password.
Invalid_number This exception is raised if the conversion of a character
string to a number fails because the string does not
represent a valid number. For example, inserting ‘John’ for a
column of type number will raise this exception.
Too_many_rows Raised when the select into statement returns more than one
row.

/*Program to understand Predefined Exception Handling*/

DECLARE

er emp%rowtype;

BEGIN

select * into er from emp where empno=&eno;

dbms_output.put_line('employee name is '||er.ename);

EXCEPTION

when no_data_found then

dbms_output.put_line('specified employee not found ------Try Again-----');

END;
User –Defined Exceptions :

PL/SQL allows you to define exceptions of your own. Unlike


predefined exceptions, user defined exceptions must be declared and must be declared
and must be raised explicitly by RAISE Statements

Syntax:

DECLARE

<Exception name> Exception

BEGIN

SQL sentence;

IF <condition> THEN

RAISE <Exception name>;

END IF;

EXCEPTION

WHEN <exception name> THEN

{user defined action to be taken};

END;

/* Program T0 Understand Userdefined Exception Handling */

DECLARE

er emp%rowtype;
errnumber number;

errmess varchar2(100);

BEGIN

SELECT * INTO er FROM emp WHERE empno = &eno;

dbms_output.put_line('EMPLOYEE NAME IS ' || er.ename);

INSERT INTO emp(empno,ename,deptno,sal) VALUES

(&eno,'&name',&dno,&salary);

EXCEPTION

When NO_DATA_FOUND then

dbms_output.put_line('SPECIFIED EMPLOYEE NOT FOUND --- TRY AGAIN ---');

When DUP_VAL_ON_INDEX Then

dbms_output.put_line ('EMPLOYEE NUMBER ALREADY EXISTS --- TRY WITH


ANOTHER NUMBER ---');

END;

CURSORS

The Oracle Engine uses a work area for its internal processing in order
to execute an SQL statement written in PL/SQL code. This work area is private to
SQL ‘s operations and is called a Cursor.

The data that is stored in the in the cursor is called the Active Data Set.
Types of cursor Cursors are classified as
1. IMPLICIT CURSORS

1. EXPLICIT CURSORS

1. Implicit Cursors :If the oracle engine for its internal processing has opened a
cursor they are known as implicit cursors. This can contain only one record while
retrieving data from table and this is closed immediately after the transaction is over.

General attributes : When the oracle engine creates an implicit or explicit cursor,
cursor control variables are also created to control the execution of the cursor.
Whenever any cursor is opened and used ,the oracle engine creates a set of four system
variables which keeps track of the current status of a cursor.

Both implicit and explicit cursors have four attributes. They are

%ISOPEN Returns TRUE if cursor is open, otherwise FALSE.

%FOUND Returns TRUE if record was fetched successfully, otherwise FALSE.

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


otherwise.

%ROWCOUNT Returns number of records processed from the cursor.

/* Program To Understand Implicit Cursors. */

BEGIN

update emp set sal = 3500 where deptno=&dno;


if (sql%found =true) then

dbms_output.put_line('records found');

dbms_output.put_line(sql%rowcount || 'records updated');

else

dbms_output.put_line('records not found');

end if;

if (sql%isopen =true) then

dbms_output.put_line('cursor is open state');

else

dbms_output.put_line('cursor is closed state');

end if;

END;

1. Explicit Cursor : Explicit cursor is created by user to store multiple records in


cursor. In this case explicit cursor is in open state until you read the last record
and close it.

Procedure to create and use explicit cursor:

1. create cursor.

2. open cursor.

3. read /fetch current record in to PL/SQL variables until last


record(use loop).
4. close cursor.

/* Program To Understand Explicit Cursors */

DECLARE

cursor ec is select * from emp;

er emp%rowtype;

BEGIN

open ec;

loop

fetch ec into er;

exit when ec%notfound;

dbms_output.put_line('employee :: ' ||ec%rowcount);

dbms_output.put_line('name is ::' ||er.ename);

dbms_output.put_line('salary :: '||er.sal);

end loop;

close ec;

END ;
STORED PROCEDURES AND 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 have been compiled and stored in one of the Oracle
engine’s system tables.

Procedures and Functions are made up of :

1. A declarative part.

2. An executable part, and

3. An optional exception-handling part.

Advantages of using a Procedure :

1. security : Stored procedures and functions can help enforce data security.

2. performance : It improves database performance in the following ways:

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

4. Productivity : By writing procedures and functions redundant coding can be


avoided, increasing productivity.

5. 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’s they become a part of the engine’s resource. Hence the
responsibility of maintaining their integrity rests with the oracle engine.

Syntax for creating a Procedure :

CREATE OR REPLACE PROCEDURE <proced name> ( arg { IN, OUT, IN OUT}


datatype …)

IS

Variable declarations

Constant declarations

BEGIN

PL/SQL subprogram body;

EXCEPTION

Exception PL/SQL block;

END;

DATABASE TRIGGERS

The Oracle engine allows the user to define procedures that are
implicitly executed (i.e. executed by the oracle engine itself), when an insert update or
delete is issued against a table from SQL* PLUS or through an application. These
procedures are called database triggers. The major issue that makes these triggers
stand-alone is that they are fired implicitly (i.e. internally) by the Oracle engine itself
and not explicitly called by the user.
Use of Database Triggers:
1. A Trigger can permit DML statements against a table only if they are
issued, during regular business hours or on predetermined weekdays.
2. A Trigger can also be used to keep an audit trail of a table (i.e. to store
the modified and deleted records of the table.)
a) It can be used to prevent invalid transactions.
b) Enforce complex security authorizations.

When a trigger is fired, an SQL statement inside the trigger’s PL/SQL code block
can also fire the same or some other trigger. This is called cascading, triggers.

Differences between Triggers and Procedures

1. Triggers do not accept parameters whereas


procedures can.
2. A trigger is executed implicitly by the Oracle engine
itself upon modification of an associated table or its
data. To execute a procedure ,it has to be explicitly
called by the user.

Trigger has three basic parts:


1. A triggering event or statement.
2. A trigger restriction
3. A trigger action

1. Triggering event or statement :


It is a SQL statement that causes a trigger to be fired. It can
be INSERT , UPDATE or DELETE statement for a specific table.

2. Trigger restriction :
A trigger restriction specifies a Boolean(logical) expression
that must be TRUE for the trigger to fire. It is an option available for triggers that
are fired for each row. Its function is to conditionally control the execution of a
trigger. A trigger restriction is specified using a WHEN clause.

3. Trigger Action :
A trigger action is the PL/SQL code to be executed when a triggering
statement is encountered
and any trigger restriction evaluates to TRUE. The PL/SQL block can contain SQL
and PL/SQL statements can define PL/SQL language constructs and call stored
procedures . Additionally for row triggers , the statements the PL/SQL block have
access to column values (: new and :old) of the current row being processed.

Syntax for creating a Trigger:

CREATE OR REPLACE TRIGGER <trigger name>


{BEFORE,AFTER}
{DELETE,INSERT,UPDATE} ON <table name>
FOR EACH ROW [WHEN condition]
DECLARE
Variable declarations;
Constant declarations;
BEGIN
PL/SQL subprogram body;
EXCEPTION
Exception PL/SQL block;
END;

You might also like