Unit 4
Unit 4
) PL SQL Programming
Session outline
Introduction to Pl SQL
Advantages of PL SQL
PL SQL Block Structure
Variable and Constants
Introduction to SQL
PLSQL Programming language
extension to SQL
It is used in the oracle server, and client
application development tools such as
oracle forms
It includes datatypes, control structures,
Procedures, functions etc…
Advantages of PL SQL
1. Integrate procedural constructs with
SQL
2. Improved performance
3. Modularized program development
4. Portability
5. Exception Handling
6. Built in libraries and packages
Variables
Variable is placeholders that store values
which can be changed through PL SQL
block
Syntax:
variable_name datatype [NOT
NULL:=value];
Where,Variable_name is name of variable, suitable data
type to store values , NOT NULL and value is optional used
to initialize data type
E.g. DECLARE
salary number(5);
Control Structure
Conditional control :- If, If…then….else,
If.. Then…elseif, Case
Iterative control:- PLSQL Basic loop,
PLSQL While loop, PLSQL FOR loop,
Nested loops in PLSQL
Sequential control:- Labeling loop,
Continue statement, Goto Statement
Conditional Control
If Then Statement:- If condition is true the
statement is executed otherwise the IF
statement does nothing.
Syntax:- IF condition THEN
statements
END IF;
E.g. IF (a == 0) THEN
a:=a+1;
END IF
Conditional Statement
IF THEN ELSE :- When both true and false side of condition
is important, then true side part executed when condition
satisfies otherwise false side part is executed
Syntax:- IF condition THEN
S1
ELSE
S2
END IF;
e.g. IF shape == Square THEN
dbms_output.put_line (‘It is square’);
ELSE
dbms_output.pit_line (‘It not square’);
END IF;
Conditional control
IF THEN ELSEIF:- This statement allows you
to add multiple conditions with series of elif
statements.
Syntax:-
IF (expression1) THEN
S1;
ELSEIF (expression 2) THEN
s2;
ELSE
S3;
END IF
CASE Statement
Case Statement selects sequence of
statement to execute with selector instead
of Boolean expression used in IF statement.
Syntax:-
CASE selector
WHEN ‘value1’ THEN S1;
WHEN ‘value2’ THEN S2;
WHWN ‘value3’ THEN S3;…
ELSE Sn; -- default case
END CASE;
Database management system 14
Matoshri Aasarabai Polytechnic, Nashik (Comp Engg.) PL SQL Programming
CASE Example
DECLARE
Grade char(1) := ‘A’;
BEGIN
CASE grade
When ‘A’ then
dbms_output.put_line(‘Excellent’);
When ‘B’ then
dbms_output.put_line(‘verygood’);
Else dbms_output.put_line(‘No such grade’);
END CASE;
END;
Database management system 15
Matoshri Aasarabai Polytechnic, Nashik (Comp Engg.) PL SQL Programming
Session assignment
Explain IF..ELSE statement.
Define Variable & Constant.
Explain PL SQL block structure,
THANK YOU
Contact mail- [email protected]
Session outline
Iterative control
Basic loop
While loop
For loop
Reverse for loop
Nested loops
Iterative control
Iterative control is also called as loop
statement.
It allows to execute group of statement
multiple times.
Types of loops:
1. PLSQL Basic Loop
2. PLSQL While Loop
3. PLSQL For Loop
4. Nested Loops in PLSQL
WHILE LOOP
A While loop statement in PLSQL
programming language repeatedly
executes a target statement as long as a
given condition is true.
Syntax:- WHILE condition LOOP
sequence_of_statements
END LOOP;
Nested Loop
IN PLSQL , we can have Loop inside loop known
as nested loops
Syntax:- LOOP
sequence of statements1
LOOP
sequence of statement2
END LOOP;
END LOOP;
Session assignment
Explain While loop with syntax and
example.
Write a short note on nested loops.
Write a code in Pl Sql to print 1 to 20
numbers using basic loop.
THANK YOU
Contact mail- [email protected]
Session outline
Sequential control
Exception handling
Raising exception
user defined exception
Predefined exceptions
Sequential control
1. Labeling a loop
3. CONTINUE statement
4. GOTO Statement
Labeling a Loop
PLSQL Loops can be labeled.
The label should be enclosed by double
angle brackets as ‘<<‘ and ‘>>’
It is written at the beginning of the loop .
The labels can also be used with exit
statement to exit from the loop.
CONTINUE Statement
This statement is used to skip remainder portion of the body,
and immediately retest its condition prior to reiterating.
DECLARE
a number(2) := 10;
BEGIN
WHILE a<20 LOOP
Dbms_output.put_line(‘values of a:’ !!a);
A :=a+1;
CONTINUE;
END IF;
END LOOP;
END;
/
GOTO Statement
The transfers control to the labelled
statement.
A GOTO statement in PLSQL programming
language provides an unconditional jump
from GOTO to a labeled statement in same
program.
Syntax:- GOTO label;
…..
<< label >>
Statement;
Exception Handling
An exception is an error condition during
a program execution
Using exception block programmer can
catch such condition and can take suitable
action
There are two types of exceptions-
1. System defined Exceptions
2. User Defined Exceptions
Example of Exception
Exception
WHEN no_data found THEN
dbms_output.put_line(‘No such
customer’);
WHEN others THEN
dbms_output.put_line(‘Error’);
END;
Raising exception
By default database server raise exception whenever
there is any internal error.
But exceptions can also be raised by programmer using
RAISE command
Syntax:- DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
Statement;
END;
Pre-Defined Exception
PLSQL provides many pre-defined
exceptions, Which are executed when any
database rule is violated by a program.
e.g.
NO_DATA_FOUND, ACCESS_INTO_NULL,
ZERO_DIVIDE,VALUE_ERROR etc…
Session assignment
Explain Continue and Goto statements.
What is exception handling? Write its
syntax.
Write a short note on 1) user defined
exceptions 2) Pre defined exceptions
THANK YOU
Contact mail- [email protected]
Session outline
Introduction to cursors
Types of cursors
Cursor attributes
Procedures
advantages syntax and example of
procedure
Database management system 46
Matoshri Aasarabai Polytechnic, Nashik (Comp Engg.) PL SQL Programming
Cursors
Oracle creates memory area for processing
SQL queries, this area is also known as
context area.
A cursor is a pointer to this context area.
The context area is controlled by the cursor.
The set of rows the cursor holds is referred
to as the active set.
Two types of cursors:-
1. Implicit cursors
2. Explicit cursors
Database management system 47
Matoshri Aasarabai Polytechnic, Nashik (Comp Engg.) PL SQL Programming
Implicit cursors
Implicit cursors are automatically created
by oracle whenever an SQL statement is
executed.
Programmer cannot control implicit
cursor.
For INSERT cursor holds data and for
UPDATE & DELETE cursor identifies
rows affected
SQL attributes:- %found, %notfound,
%isopen, %rowcount
Database management system 48
Matoshri Aasarabai Polytechnic, Nashik (Comp Engg.) PL SQL Programming
Cursor attributes
1. %FOUND:- Returns true if insert,
update or delete statement affected one
or more rows. Otherwise returns false.
2. %NOTFOUND:- It is opposite of
%FOUND. It returns true if insert,
update or delete statements affected no
rows. Otherwise returns false
Cursor attributes
3. %ISOPEN:- Always returns False for
implicit cursors, because oracle closes the
sql cursor automatically after executing its
related sql statements.
Example on cursor
Declare
Total_rows number(2);
Begin
Update customers set salary = salary +200;
If sql%notfound then
Dbms_output.put_line(‘no customer selected’);
Elseif sql%found then
total_rows := sql%rowcount;
Dbms_output.put_line(total_rows !! ‘customers selected’);
END IF;
END;
/
Database management system 51
Matoshri Aasarabai Polytechnic, Nashik (Comp Engg.) PL SQL Programming
Explicit cursor
Explicit cursors are programmer defined
cursors for having more control over
context area.
Explicit cursor is defined in declaration
section.
It is created on select statement.
Syntax:- cursor cursor_name is
select_statement;
Procedure
A stored procedure is prepared SQL
code that you save so you and reuse the
code repeatedly.
we can execute stored procedure with
passing parameters too.
So the stored procedures can be used
with any application as per expectations
of output.
Modes in procedure
1. IN:- This type of parameter is passed to
the procedure as read only value that
cannot be changed in the procedure.
2. OUT:- This type od parameter is write
only and only appear on left side of an
assignment statement in the procedure.
3. IN OUT:- Combination of IN & OUT.
The parameter of this procedure is
passed to the procedure and value can
be changed in the procedure.
Database management system 59
Matoshri Aasarabai Polytechnic, Nashik (Comp Engg.) PL SQL Programming
Session assignment
What is cursor? Give its types.
Explain cursor attributes.
Write steps to create explicit cursor
Explain procedure with syntax and
example.
THANK YOU
Contact mail- [email protected]
Session outline
Functions
Advantages of functions
Example of function
Data base triggers
syntax and example.
creating and dropping triggers
Functions
Function is similar to procedure.
The difference is function returns a value.
A function can accept many zero or non
zero parameters, and it returns only one
value.
The data type of return value is written
or declared in the header of the function.
Advantages of functions
Code Reusability
Saves time and cost
It return value
Argument can be passed at run time to
get desired result
Function increases flexibility of program
better for client server type of
opeartion.
Creating functions
Syntax:- CREATE OR REPLACE FUNCTION
<function name>, parameter1 name> <mode>
<data type>,….)
RETURN <function return value data type> IS
<variable declarations>
BEGIN
Executable commands
Return (return value);
…
EXECEPTION
Exceptions handlers
END
Example of function
CREATE OR REPLACE FUNCTION myfunc1
RETURN NUMBER
IS
ret_sal NUMBER(10,2);
BEGIN
SELECT emp_salary INTO ret_sal FROM employee WHERE
emp_id = ‘101’;
Return(ret_sal);
END myfunc1;
/
[Note:- to check function is created use
SQL>@func1;
Function created.
Function Execution
To execute function use:
SQL> var par_sal varchar(20);
SQL> EXECUTE : par_sal := myfunc2;
SQL> print par_sal;
Dropping function:-
To delete created function from database
use:
DROP FUNCTION <functionname>;
Database Triggers
Database trigger is stored PL/SQL program
unit associated with a specific database table.
when given SQL statement affect the table
trigger automatically executed by oracle
implicitly.
You can associate 12 database triggers with
a given table.
The database trigger has 3 parts: a triggering
event, an optional trigger constraint and a
trigger action.
Creating Trigger
Syntax:-
CREATE OR REPLACE TRIGGER trigger_name
{BEFORE!AFTER} triggering_event ON table_name
[FOR EACH ROW]
[WHEN condition]
DECLARE
Declaration statements
BEGIN
Executable statements
EXCEPTION
Exception-handling statements
END;
Database management system 71
Matoshri Aasarabai Polytechnic, Nashik (Comp Engg.) PL SQL Programming
Syntax parameters
CREATE – specifies that new trigger is creating
REPLACE- specifies that modification of existing
trigger.[OR REPLACE is optional]
BEFORE /AFTER- specify that when trigger is
fired. (Types of trigger)
Trigger event is DML statement against table.
Table_name is ia name of associated table
FOR EACH ROW- specifies a trigger is a row
trigger
WHEN- specifies condition for trigger to be fired
[Note – once the associated table is drooped , all triggers for table is also
dropped.]
Parts of Trigger
Database trigger has 3 parts:-
1. Trigger statement:- These are DML
statements like UPDATE, INSERT or
DELETE. it executes trigger when
condition is met.
2. Trigger body:- It is the procedure that
contains SQL or PL/SQL code to be
executed for triggering statement.
3. Trigger restriction:- Restriction on trigger
can be set using WHEN clause. It is used to
specify condition for trigger to be fired.
Executing trigger
A statement trigger is fired only once for
triggering statement.
If some set of condition is applied on
database, trigger used to restrict user
firing trigger.
Error message or warning is issued to
user according to trigger specified.
RAISE_APPLICATION_ERROR can aslo
be used to display error with defined
number.
Database management system 74
Matoshri Aasarabai Polytechnic, Nashik (Comp Engg.) PL SQL Programming
Dropping Triggers
The delete complete occurrence of
trigger from database drop command is
used.
Syntax:-
drop trigger trigger_name;
E.g. drop trigger mytrig1;
Session assignment
Explain function with example.
What is database triggers? Give its
syntax.
Explain how to create and drop trigger.
THANK YOU
Contact mail- [email protected]