You are on page 1of 54

INTRODUCTION AND NEED OF

PL/SQL

PL/SQL is a database-oriented programming


language that extends Oracle SQL with
procedural capabilities. PL/SQL is a block-
structured query language which combines the
features of SQL with procedural capabilities.
Advantages of PL/SQL
• PL/SQL has SQL features as well as
procedural capabilities.
• PL/SQL sends entire block of SQL statements
to Oracle engine in one go. Thus, it reduces
the network traffic which results in an increase
of speed of data processing.
• PL/SQL allows the programmers to display
user-friendly error messages.
• PL/SQL programs are portable i.e., these can
run on any computer hardware and operating
system where Oracle is installed.
PL/SQL ARCHITECTURE
STRUCTURE OF PL/SQL CODE
BLOCK
DECLARE
Variable and constant declarations
BEGIN
SQL and PL statements
EXCEPTION
Error handling statements
END;
FUNDAMENTALS OF PL/SQL

• Character set
• Operators
• Literals
• Variables and constants
• Data types
• Declarations
• Assignments
• Comments
Declarations
Before a variable can be used in the begin section, it must be
declared in the declare section. The syntax for declaring a
variable is as follows:

Syntax:
Variable-name datatype (size);

Examples:

Age Number(5);
A Number(10,2);
Name Varchar2(20);
DOB Date;
Declarations

The syntax for declaring a constant is as follows:


Syntax:
Variable-name Constant datatype (size) := Value;
Example:
Pi Constant Number(4,2) := 3.14;
Assignments

For manipulating data in the begin section,


variables must be assigned some value. A
variable can be assigned a value in two ways
by using:
• Assignment operator (:=) to get the value from
the user.
• SELECT INTO clause to get the value from
database object.
Assignments
Some examples using assignment operator are:
A := 10;
B := c + d;
Sal := Salary+1000;
Example using SELECT INTO clause:
Select salary into sal from employee where
empid = 12;
Comments
Adding comments to a program increases
readability and understanding of the program.
Generally, comments are used to describe the
purpose and use of each code segment.
PL/SQL supports two comment styles:
• Single-line comments and
• Multi-line comments
Comments
• Single-line comments begin with a double hyphen (--)
anywhere on a line and extend to the end of the line.
For example:
A := 5; -- assign value 5 to variable A
• Multi-line comments begin with a slash-asterisk (/*),
end with an asterisk-slash (*/) and can span multiple
lines. For examples:
A := b + c; /* the values of variables b and c are
added and result is assigned to
variable A */
READ A VALUE DURING RUN
TIME

The symbol & is used for this purpose. For


example, consider the num variable. Then, to
read the value for this variable during run
time, following statement can be used:

Num := #
%TYPE AND %ROWTYPE

PL/SQL variables and cursors have attributes,


which are the properties that enable us to refer
the data type and structure of an item from the
database without repeating its definition.
These attributes are %TYPE and %ROWTYPE.
%TYPE AND %ROWTYPE
%TYPE

%TYPE attribute provides the data type of a


variable or database column. This is
particularly useful when declaring variables
that will hold database values. For Example:
sal employee.salary%TYPE;
%TYPE AND %ROWTYPE

%ROWTYPE

In PL/SQL, records are used to group data. A record


consists of a number of related fields in which data
values can be stored. The %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. Columns in a row and corresponding
fields in a record have the same names and datatypes.
%TYPE AND %ROWTYPE

%ROWTYPE
dept_rec dept%ROWTYPE;
Now to refer the fields, dot notation can be used
as shown in the following example:
dept_rec.deptno;
dept_rec.deptname;
DISPLAYING USER MESSAGE
ON THE SCREEN

To display a message, the SERVEROUTPUT


should be set ON. The syntax for this is as
follows:

Syntax:
SQL> SET SERVEROUTPUT ON;
DISPLAYING USER MESSAGE
ON THE SCREEN
• Now we can display any message using
DBMS_OUTPUT.PUT_LINE command as follows:
DBMS_OUTPUT.PUT_LINE(‘Well Come To Computer Lab’);
• To display value of a variable A, following command can be
used:
DBMS_OUTPUT.PUT_LINE (A);
To display value of a variable A along with some message,
following command can be used:

DBMS_OUTPUT.PUT_LINE (‘Value of A is’ || A);


SOME BASIC PL/SQL
PROGRAMS
• Write a PL/SQL code block to display the
message, ‘Hello’ .

Begin
dbms_output.put_line ('Hello');
End;
SOME BASIC PL/SQL
PROGRAMS
• Write a PL/SQL code block to add two
numbers and display the addition.
Declare
a number(2);
b number(2);
c number(2);
Begin
a:=5;
b:=4;
c:=a + b;
dbms_output.put_line ('sum='||c);
End;
SOME BASIC PL/SQL
PROGRAMS
Declare
a number(5);
b number(5);
t number(6);
Begin
Select ta, da into a, b from emp where empid = 8;
t := a + b;
Update emp set total = t where empid = 8;
End;
SOME BASIC PL/SQL
PROGRAMS
Declare
a emp.ta%type;
b emp.da%type;
t emp.total%type;
Begin
Select ta, da into a, b from emp where empid = 8;
t := a + b;
Update emp set total = t where empid = 8;
End;
SOME BASIC PL/SQL
PROGRAMS

Declare
Record emp%rowtype;
Begin
Select*into Record from emp where empid = 8;
Record.total := Record.ta + Record.da;
Update emp set total=Record.total where empid = 8;
End;
CONTROL STATEMENTS

PL/SQL allows us to change the flow of control


by using either of the followings:

• Conditional control
• Iterative control
• Sequence control
Conditional Control

Sometimes, it becomes necessary to take


alternative actions depending on
circumstances. The IF statement is used for
this purpose. There are three forms of IF
statements:
• IF-THEN statement
• IF-THEN-ELSE statement
• IF-THEN-ELSIF statement
Conditional Control
• If-Then statement
If the condition is evaluated to true, then the sequence
of statements is executed. If the condition is
evaluated to false then, IF statement does nothing. In
either case, control passes to the next statement.
The Syntax for IF-THEN statement is as follows:
Syntax:
IF condition THEN
Sequence-of-statements;
END IF;
Conditional Control
• If-Then-Else statement
The IF-THEN-ELSE statement is used to execute a
sequence of statements conditionally. The IF clause
checks a condition, the THEN clause defines what to
do if the condition is true and the ELSE clause
defines what to do if the condition is false.
Syntax:
IF condition THEN
Sequence-of-statements1;
ELSE
Sequence-of-statements2;
END IF;
Conditional Control
• Write a program to find largest of two
numbers.
Declare
num1 number(2);
num2 number(2);
Begin
num1:=&num1;
num2:=&num2;
IF num1 > num2 THEN
dbms_output.put_line('greater is num1='||num1);
ELSE
dbms_output.put_line('greater is num2='||num2);
END IF;
End;
Conditional Control
• If-Then-Elseif statement
If some action has to be taken for more than two comparisons,
then IF-THEN-ELSEIF statement can be used.
Syntax:
IF condition1 THEN
Sequence-of-statements1;
ELSIF condition2 THEN
Sequence-of-statements2;
ELSE
Sequence-of-statements3;
END IF;
Iterative Control

Iterative statements are used to execute a


sequence of statements multiple times. There
are three forms of iterative statements:
• LOOP
• WHILE-LOOP and
• FOR-LOOP
LOOP

• Syntax:

LOOP
Sequence-of-statements;
EXIT WHEN condition;
END LOOP;
LOOP
• Write a program to display the numbers
from 1 to 10.
Declare
i number(2);
Begin
i:=1;
LOOP
dbms_output.put_line(i);
i:=i + 1;
EXIT WHEN i > 10;
END LOOP;
End;
WHILE-LOOP

Syntax:

WHILE condition LOOP


Sequence-of-statements;
END LOOP;
WHILE-LOOP
• Write a program to print square of numbers
from 1 to 10.
Declare
a number(2);
Begin
a:=1;
WHILE a<=10
LOOP
dbms_output.put_line(a*a);
a:=a+1;
END LOOP;
End;
FOR-LOOP

• Syntax:

FOR counter IN [REVERSE] lb..hb


LOOP
Sequence-of-statements;
END LOOP;
FOR-LOOP
• Write a PL/SQL block to display the
multiplication table of 2.
Declare
Total number(4);
i Number(2);
Begin
FOR i IN 1..10
LOOP
Total:=2*i;
dbms_output.put_line('2*' || i || '=' ||Total);
END LOOP;
End;
Sequence Control

• Syntax:

GOTO label-name;
Sequence Control
Declare
num1 number(2);
num2 number(2);
Begin
num1:=&num1;
num2:=&num2;
IF num1 > num2 THEN
GOTO O1;
ELSE
GOTO O2;
END IF;
<<O1>>
dbms_output.put_line('greater is num1='||num1);
GOTO O3;
<<O2>>
dbms_output.put_line('greater is num2='||num2);
<<O3>>
dbms_output.put_line('successful');
End;
Triggers
Database trigger is the stored procedure that is
automatically executed in response to certain events on
a particular table or view in a database. An event on a
table can be INSERT, DELETE or UPDATE statement
on that table
Triggers Procedures

1. Triggers do not accept 1. Procedures can accept


parameters. parameters.
2. A trigger is executed 2. A procedure is executed when
automatically without user explicitly called by a user.
calling.
NEED AND USES OF
TRIGGERS
• prevent changes (e.g. prevent an invoice from being
changed after it's been mailed out).
• log changes (e.g. keep a copy of the old data).
• audit changes (e.g. keep a log of the users and roles
involved in changes).
• enhance changes (e.g. ensure that every change to a
record is time-stamped by the server's clock, not the
client's).
• replicate data (e.g. store a record of every change to be
shipped to another database later).
• enhance performance (e.g. update the account balance
after every detail transaction for faster queries).
Parts of a Trigger

• There are three parts of a trigger and they


are:
 
• Triggering event or statement
• Trigger restriction
• Trigger action
TYPES OF TRIGGERS
• There are two classes of triggers and they are:
 
• ROW triggers
• STATEMENT triggers

Another classification of triggers is based on the execution


time of a trigger and they are:
• BEFORE trigger
• AFTER trigger
CREATING A TRIGGER
• Syntax:
CREATE OR REPLACE TRIGGER TriggerName
BEFORE / AFTER
DELETE / INSERT / UPDATE OF ColumnName
ON TableNamne
REFERENCING OLD AS old, NEW AS new
FOR EACH ROW
WHEN Condition
DECLARE
Variable and Constant Declarations;
BEGIN
SQL and PL/SQL statements;
EXCEPTION
Error Handling Statements;
END;
Cursors
• When a select statement is executed to access the data
from a table then, the Oracle engine needs a work area
for query execution and to store the result of that query at
server side.

• A cursor is a work area where the result of a SQL query is


stored at the server side. The contents of a cursor are
then displayed at the client machine via a network. The
data stored in a cursor is called as ‘active data set’.
Working with cursors needs to:
•  Declare a cursor
• Open a cursor
• Fetch or Read from cursor
• Close a cursor
Cursors
Types of Cursors
On the basis of how cursors are managed, there are two types of
cursors and these are:
• Implicit cursor
• Explicit cursor
•Implicit Cursor
It is a work area that is declared, opened and closed internally by the
Oracle engine. The user is not involved in the process of managing the
cursor. PL/SQL declares a cursor implicitly for all SQL data
manipulation statements including queries that return only one row.
•Explicit Cursor
It is a work area that is declared, opened and closed externally by the
user. It is also called as user-defined cursors. When a query returns
multiple rows, user can explicitly declare a cursor to process the rows.
Explicit cursor is declared in the DECLARE part of a PL/SQL block.
Cursors
General Cursor Attributes
Attribute Meaning

%ISOPEN Returns TRUE if cursor is open, FALSE


otherwise.

%FOUND Returns TRUE if record was fetched


successfully, FALSE otherwise.

%NOTFOUND Returns TRUE if record was not fetched


successfully, FALSE otherwise.

%ROWCOUNT Returns number of records processed from


cursor.
Cursors
Implicit Cursor
•Implicit cursor is declared, opened and closed internally by the Oracle engine.
The user is not involved in the process of managing the cursor. Implicit cursor
attributes are used to access the information about the status of last insert,
update, and delete or single-row select statement. Implicit cursor uses same
set of general attributes (discussed above) but proceeded with cursor name
i.e., SQL. The implicit cursor attributes are:

•SQL%ISOPEN
•SQL%FOUND
•SQL%NOTFOUND
•SQL%ROWCOUNT
 
•SQL%ISOPEN is always FALSE because the Oracle engine closes the
implicit cursor automatically after executing the SQL statement. The meaning of
other three attributes is same as that of general cursor attributes as mentioned
above in the attribute table.
Cursors
• Explicit Cursor

When a query returns multiple rows, user can explicitly declare a


cursor to process the rows. Explicit cursor is declared in the
DECLARE part of a PL/SQL block. All the general attributes of a
cursor are applicable to explicit cursor with same meaning. Explicit
cursor attributes are:

• %ISOPEN
• %FOUND
• %NOTFOUND
• %ROWCOUNT
Cursors
Steps in Handling Explicit Cursor

The explicit cursor handling needs following steps to be followed:

•Declare the cursor in the DECLARE part of PL/SQL block.


•Open the cursor.
•Using a loop, fetch data from cursor one row at a time into memory
variables and process the data stored in the memory variables as
required.
•Exit from the loop after the processing is complete.
•Close the cursor.
Cursors
Declaring a Cursor

•A cursor must be declared before referencing it in other statements. Explicit


cursor is declared in the DECLARE part of a PL/SQL block. When a cursor is
declared, it is given a name and is associated with a specific query using the
following syntax:

•Syntax:
Cursor CursorName IS SELECT statement;
 
•Here, SELECT statement can use all its clauses except INTO clause.
 
•Example:

Cursor C IS SELECT rollno, name from student where branch=’CSE’;


Cursors
• Opening a Cursor

• Opening a cursor executes the query and identifies the result set,
which consists of all rows that meet the query search criteria. The
syntax for opening a cursor is as follows:
•  
• Syntax:
Open CursorName;

• Example:
Open C;
Cursors
• Fetching a Record from Cursor
After opening a cursor, FETCH statement is used to load the rows from
the result set into the memory variables but, one row at a time. After
each fetch, the cursor advances to the next row in the result set.
The syntax for FETCH is as follows:
• Syntax:
• FETCH CursorName INTO Variables;

• For each column value returned by the query associated with the
cursor, there must be a corresponding, type-compatible variable in
the INTO list.
 
• Example:
FETCH C INTO my_rollno, my_name;

Here, my_rollno and my_name are the memory variables.


Cursors
• Fetching a Record from Cursor
LOOP
FETCH C INTO my_record;
EXIT WHEN C%NOTFOUND;
-- Process data record
END LOOP;

Here, my_record is a record variable that is declared using %ROWTYPE


Cursors
• Closing a Cursor

CLOSE statement is used to close a cursor. It disables the cursor and


the result set becomes undefined. Once a cursor is closed, it can be
reopened again. The syntax for CLOSE is as follows:
 
• Syntax:
CLOSE CursorName;
 
• Example:
CLOSE C;

You might also like