0% found this document useful (0 votes)
103 views87 pages

DMS (22319) - Chapter 4 Notes

The document discusses PL/SQL programming including PL/SQL block structure, data types, variables, constants, control structures like conditional and iterative control, and the PL/SQL execution environment. Key aspects covered include if-then-else conditional statements, loops, declaring and assigning variables and constants, and how PL/SQL code is executed.

Uploaded by

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

DMS (22319) - Chapter 4 Notes

The document discusses PL/SQL programming including PL/SQL block structure, data types, variables, constants, control structures like conditional and iterative control, and the PL/SQL execution environment. Key aspects covered include if-then-else conditional statements, loops, declaring and assigning variables and constants, and how PL/SQL code is executed.

Uploaded by

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

Unit-IV:

PLSQL PROGRAMMING
Marks:16

Database Management System (DMS) Mr. S. Y. Divekar


Database Management System (DMS) Mr. S. Y. Divekar
Topic:- 4.1 : Outlines
PL / SQL :
Introduction of PL/SQL.
Advantages of PL/SQL.
PL/SQL Block Structure.
PL/SQL Execution Environment.
PL/SQL Data Type.
PL/SQL Variables.
PL/SQL Constant.

Database Management System (DMS) Mr. S. Y. Divekar


PL/SQL Introduction:
Stands for Procedural Language extension to SQL.
PL/SQL is a block structured language that enables developers to
combine the power of SQL with procedural statements. All the
statements of a block are passed to oracle engine all at once
which increases processing speed and decreases the traffic.
PL/SQL: Provides a block structure for executable units of code.
Maintenance of code is made easier with such a well-defined
structure.

Provides procedural constructs such as:


– Variables, constants, and types
– Control structures such as conditional statements and loops
– Reusable program units that are written once and executed
many times
Database Management System (DMS) Mr. S. Y. Divekar
Disadvantages of SQL:
SQL doesn’t provide the programmers with a technique of
condition checking, looping and branching.
SQL statements are passed to Oracle engine one at a time which
increases traffic and decreases speed.
SQL has no facility of error checking during manipulation of data.
Features of PL/SQL
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.

Database Management System (DMS) Mr. S. Y. Divekar


Advantages of PL/SQL:
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.
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.
PL/SQL gives high productivity to programmers as it can query,
transform, and update data in a database.
PL/SQL saves time on design and debugging by strong features, such as
exception handling, encapsulation, data hiding, and object-oriented
data types.
Applications written in PL/SQL are fully portable.
PL/SQL provides high security level.
PL/SQL provides support for Object-Oriented Programming.
PL/SQL provides support for developing Web Applications and Server
Pages.
Database Management System (DMS) Mr. S. Y. Divekar
PL/SQL Block Structure:
The basic unit in PL/SQL is a block. All PL/SQL programs are made
up of blocks, which can be nested within each other.

Declare section starts with DECLARE keyword in which variables,


constants, records as cursors can be declared which stores data
temporarily. It basically consists definition of PL/SQL identifiers.
This part of the code is optional.

Database Management System (DMS) Mr. S. Y. Divekar


PL/SQL Block Structure:
Execution section starts with BEGIN and ends with END keyword.
This is a mandatory section and here the program logic is written
to perform any task like loops and conditional statements. It
supports all DML commands, DDL commands and SQL*PLUS built-
in functions as well.
Exception section starts with EXCEPTION keyword. This section is
optional which contains statements that are executed when a
run-time error occurs. Any exceptions can be handled in this
section.

Database Management System (DMS) Mr. S. Y. Divekar


PL/SQL Environment:
ORACLE PL/SQL is an extension of SQL language that combines
the data manipulation power of SQL with the processing power of
procedural language to create super powerful SQL queries.
PL/SQL means instructing the compiler 'what to do' through SQL
and 'how to do' through its procedural way.
The PL/SQL architecture mainly consists of following three
components:
PL/SQL block
PL/SQL Engine
Database Server

Database Management System (DMS) Mr. S. Y. Divekar


PL/SQL Environment: PL/SQL block:
This is the component which has the actual PL/SQL code.
This consists of different sections to divide the code logically
(declarative section for declaring purpose, execution section for
processing statements, exception handling section for handling
errors)
It also contains the SQL instruction that used to interact with the
database server.
All the PL/SQL units are treated as PL/SQL blocks, and this is the
starting stage of the architecture which serves as the primary
input.
Following are the different type of PL/SQL units.
1. Anonymous Block 2. Function 3. Library
4. Procedure 5.Package Body 6.PackageSpecification
7. Trigger 8.Type 9.Type Body

Database Management System (DMS) Mr. S. Y. Divekar


PL/SQL Environment: PL/SQL Engine:
PL/SQL engine is the component where the actual processing of
the codes takes place.
PL/SQL engine separates PL/SQL units and SQL part in the input
(as shown in the image below).
The separated PL/SQL units will be handled by the PL/SQL engine
itself.
The SQL part will be sent to database server where the actual
interaction with database takes place.
It can be installed in both database server and in the application
server.

Database Management System (DMS) Mr. S. Y. Divekar


PL/SQL Environment: Database Server:
This is the most important component of Pl/SQL unit which
stores the data.
The PL/SQL engine uses the SQL from PL/SQL units to interact
with the database server.
It consists of SQL executor which parses the input SQL statements
and execute the same.

Database Management System (DMS) Mr. S. Y. Divekar


PL/SQL - Data Types:

The PL/SQL variables, constants and parameters must have a valid


data type, which specifies a storage format, constraints, and a
valid range of values.

Database Management System (DMS) Mr. S. Y. Divekar


PL/SQL -Scalar Data Type:

Database Management System (DMS) Mr. S. Y. Divekar


PL/SQL -Scalar Data Type:

Database Management System (DMS) Mr. S. Y. Divekar


PL/SQL -Scalar Data Type:

Database Management System (DMS) Mr. S. Y. Divekar


PL/SQL -Scalar Data Type:
Example:

Database Management System (DMS) Mr. S. Y. Divekar


PL/SQL -Scalar Data Type:

Database Management System (DMS) Mr. S. Y. Divekar


PL/SQL -Scalar Data Type:

Database Management System (DMS) Mr. S. Y. Divekar


PL/SQL -Reference Data Type:
Directly reference specific database column or row
Assume data type of associated column or row
%TYPE data declaration syntax:
variable_name tablename.fieldname%TYPE;
%ROWTYPE data declaration syntax:
variable_name tablename%ROWTYPE;

Database Management System (DMS) Mr. S. Y. Divekar


PL/SQL -Variable:
PL/SQL variables must be declared in the declaration section or in
a package as a global variable. When you declare a variable,
PL/SQL allocates memory for the variable's value and the storage
location is identified by the variable name.
Syntax : Variable_name datatype(size);
Example: roll_no NUMBER(2);
a int;
set serveroutput on;
DECLARE
a NUMBER(2);
b NUMBER(2) := 5;
BEGIN
a := b;
dbms_output.put_line(a);
END;
Database Management System (DMS) Mr. S. Y. Divekar
PL/SQL –Constants :
Constants are those values which when declared remain fixed
throughout the PL/SQL block.
For declaring constants, a constant keyword is used.
Syntax : Constant_Name constant Datatype(size) := value;
Example: school_name constant VARCHAR2(20) := "DPS";
set serveroutput on;
DECLARE
school_name constant varchar2(20) := "DPS";
BEGIN
dbms_output.put_line('I study in '|| school_name);
END;

Database Management System (DMS) Mr. S. Y. Divekar


Topic:- 4.2 : Outlines
PL / SQL :Control Structure :
Conditional Control Structure,
Iterative Control ,
Sequential Control.

Database Management System (DMS) Mr. S. Y. Divekar


PL/SQL Control Structure :
PL/SQL Control Structures are used to control flow of
execution. PL/SQL provides different kinds of statements to
provide such type of procedural capabilities. These statements
are almost same as that of provided by other languages.
The flow of control statements can be classified into the following
categories:
1. Conditional / Selection Control
2. Iterative Control
3. Sequential Control

Database Management System (DMS) Mr. S. Y. Divekar


Conditional / Selection Control:
PL/SQL allows the use of an IF statement to control the execution
of a block of code.
In PL/SQL, the IF -THEN - ELSIF - ELSE - END IF construct in code
blocks allow specifying certain conditions under which a specific
block of code should be executed.
Syntax:
IF < Condition > THEN
< Action >
ELSIF <Condition> THEN
< Action >
ELSE < Action >
END IF;

Database Management System (DMS) Mr. S. Y. Divekar


Conditional / Selection Control:
Example:
DECLARE
a number(3) := 200;
BEGIN
-- check the boolean condition using if statement
IF( a < 10 ) THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 10 ' );
ELSE
dbms_output.put_line('a is not less than 10 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;

Database Management System (DMS) Mr. S. Y. Divekar


Conditional / Selection Control:
CASE Statement :
The PL/SQL CASE Statement provides facility to execute a
sequence of statements based on a selector. A selector may be
variable, function or an expression.
Syntax:
CASE [expression]
WHEN condition1 THEN result1
WHEN condition2 THEN result2
…....................
WHEN condition_n THEN result_n
ELSE result
END;

Database Management System (DMS) Mr. S. Y. Divekar


Conditional / Selection Control:
CASE Statement
Example:
DECLARE
grade char(1) := 'C';
BEGIN
CASE grade
when 'A' then dbms_output.put_line('Distinction');
when 'B' then dbms_output.put_line('First class');
when 'C' then dbms_output.put_line('Second class');
when 'D' then dbms_output.put_line('Pass class');
else dbms_output.put_line('Failed');
END CASE;
END;

Database Management System (DMS) Mr. S. Y. Divekar


Iterative Control :
Iterative control indicates the ability to repeat or skip sections of a
code block.
A loop marks a sequence of statements that has to be repeated.
The keyword loop has to be placed before the first statement in
the sequence of statements to be repeated, while the keyword
end loop is placed immediately after the last statement in the
sequence.
Once a loop begins to execute, it will go on forever. Hence a
conditional statement that controls the number of times a loop is
executed always accompanies loops.

Database Management System (DMS) Mr. S. Y. Divekar


Iterative Control :
PL/SQL supports the following structures for iterative control:
Simple loop :
In simple loop, the key word loop should be placed before the
first statement in the sequence and the keyword end loop should
be written at the end of the sequence to end the loop.
Syntax:
Loop
< Sequence of statements >
End loop;

Database Management System (DMS) Mr. S. Y. Divekar


Iterative Control :
Simple loop :
Example:
DECLARE
i number := 0;
BEGIN
LOOP
dbms_output.put_line ('i = '||i);
i:=i+1;
EXIT WHEN i>=11;
END LOOP;
END;
/

Database Management System (DMS) Mr. S. Y. Divekar


Iterative Control :
WHILE loop :
The while loop executes commands in its body as long as the
condition remains true
Syntax:

WHILE < condition >


LOOP
< Action >
END LOOP

Database Management System (DMS) Mr. S. Y. Divekar


Iterative Control :WHILE loop :
Example:
DECLARE
num Number(3) :=123;
ans Number(3) :=0;
i Number(3) :=0;
BEGIN
WHILE num != 0
LOOP
i:=mod(num,10);
ans:=(ans * 10 ) + i;
num:=floor(num/10);
END LOOP;
dbms_output.put_line('reverse of given number is: ' || ans);
END;
/
Database Management System (DMS) Mr. S. Y. Divekar
Iterative Control :
FOR loop :
The FOR loop can be used when the number of iterations to be
executed are known.
Syntax:
FOR variable IN [REVERSE] start..end
LOOP < Action >
END LOOP;

The variable in the For Loop need not be declared. Also the
increment value cannot be specified. The For Loop variable is
always incremented by 1.

Database Management System (DMS) Mr. S. Y. Divekar


Iterative Control :FOR loop :
Example:
DECLARE
i number ;
BEGIN
FOR i IN 1 .. 10
LOOP
dbms_output.put_line ('i = '||i);
END LOOP;
END; /

Database Management System (DMS) Mr. S. Y. Divekar


Sequential Control :
The sequential control statements are GOTO, which goes to a
specified statement, and NULL, which does nothing.
GOTO Statement:
The GOTO statement changes the flow of control within a PL/SQL
block. This statement allows execution of a section of code, which
is not in the normal flow of control. The entry point into such a
block of code is marked using the tags «userdefined name». The
GOTO statement can then make use of this user-defined name to
jump into that block of code for execution.
Syntax:
GOTO jump; ....
<<jump>>

Database Management System (DMS) Mr. S. Y. Divekar


Sequential Control : GOTO Statement :
Example:
DECLARE
BEGIN
dbms_output.put_line ('code starts');
dbms_output.put_line ('before GOTO statement');
GOTO down;
dbms_output.put_line ('statement will not get executed..');
<<down>>
dbms_output.put_line ('flow of execution jumped here.');
END; /

Database Management System (DMS) Mr. S. Y. Divekar


Topic:- 4.3 : Outlines
PL / SQL :Exceptional Handling :
Predefined Exception,
User Defined Exception.

Database Management System (DMS) Mr. S. Y. Divekar


Exceptional Handling :
An Exception is an error situation, which arises during program
execution. When an error occurs exception is raised, normal
execution is stopped and control transfers to exceptionhandling
part.
Exception handlers are routines written to handle the exception.
The exceptions can be internally defined (system-defined or pre-
defined) or User-defined exception.
Syntax:
EXCEPTION
WHEN <ExceptionName> THEN
<User Defined Action To Be Carried Out>

Database Management System (DMS) Mr. S. Y. Divekar


Exceptional Handling : Predefined exception :
Predefined exception is raised automatically whenever there is a
violation of Oracle coding rules.
Predefined exceptions are those like ZERO_DIVIDE, which is raised
automatically when we try to divide a number by zero.
Other built-in exceptions are given below.
You can handle unexpected Oracle errors using OTHERS handler.
It can handle all raised exceptions that are not handled by any
other handler.
It must always be written as the last handler in exception block.
Predefined exception handlers are declared globally in package
STANDARD. Hence we need not have to define them rather just
use them.

Database Management System (DMS) Mr. S. Y. Divekar


Exceptional Handling : Predefined exception :

The biggest advantage of exception handling is it improves


readability and reliability of the code. Errors from many
statements of code can be handles with a single handler. Instead
of checking for an error at every point we can just add an
exception handler and if any exception is raised it is handled by
that.
For checking errors at a specific spot it is always better to have
those statements in a separate begin – end block.
Database Management System (DMS) Mr. S. Y. Divekar
Exceptional Handling : Predefined exception :
Example:
DECLARE
N number;
BEGIN
N:=10/0;
EXCEPTION WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('divide by zero error occures..');
END;
/

Database Management System (DMS) Mr. S. Y. Divekar


Exceptional Handling : User-defined Exceptions:
The technique that is used is to bind a numbered exception
handler to a name using Pragma Exception_init ().
This binding of a numbered exception handler, to a name (i.e. a
String), is done in the Declare section of a PL/SQL block.
The Pragma action word is a call to a pre-compiler, which
immediately binds the numbered exception handler to a name
when encountered.
The function Exception_init() takes two parameters the first is the
user defined exception name the second is the Oracle engine's
exception number.
These lines will be included in the Declare section of the PL/SQL
block.
The user defined exception name must be the statement that
immediately precedes the Pragma Exception_init() statement.

Database Management System (DMS) Mr. S. Y. Divekar


Exceptional Handling : User-defined Exceptions:
Example:
DECLARE
e_MissingNull EXCEPTION;
PRAGMA EXCEPTION_INIT(e_MissingNull, -1400);
BEGIN
INSERT INTO emp(id) VALUES (NULL);
EXCEPTION
WHEN e_MissingNull THEN
DBMS_OUTPUT.PUT_LINE('ORA-1400 occurred');
END;
/

Database Management System (DMS) Mr. S. Y. Divekar


Exceptional Handling : User-defined Exceptions:
Syntax:
DECLARE
< ExceptionName > EXCEPTION ;
PRAGMA EXCEPTION_INIT (< ExceptionName >, <ErrorCodeNo>);
BEGIN
Using this technique it is possible to bind appropriate numbered exception
handlers to names and use these names in the Exception section of a PL/SQL
block.
When this is done the default exception handling code of the exception
handler is overridden and the user-defined exception handling code is
executed .
Syntax:
DECLARE
< ExceptionName > EXCEPTION ;
PRAGMA EXCEPTION_INIT (< ExceptionName >, <ErrorCodeNo>);
BEGIN
EXCEPTION
WHEN < ExceptionName > THEN < Action >
END;
Database Management System (DMS) Mr. S. Y. Divekar
User Defined Exception Handling :
To trap business rules being violated the technique of raising
user-defined exceptions and then handling them, is used.
User-defined error conditions must be declared in the declarative
part of any PL/SQL block.
In the executable part, a check for the condition that needs
special attention is made.
If that condition exists, the call to the user-defined exception is
made using a RAISE statement.
The exception once raised is then handled in the Exception
handling section of the PL/SQL code block.

Database Management System (DMS) Mr. S. Y. Divekar


User Defined Exception Handling :
Syntax:
DECLARE
< < ExceptionName > EXCEPTION ;
BEGIN
<SQL Sentence >;
IF < Condition > THEN
RAISE <ExceptionName>;
END IF;
EXCEPTION
WHEN < ExceptionName > THEN {User Defined Action To Be Taken};
END;

Database Management System (DMS) Mr. S. Y. Divekar


User Defined Exception Handling :
Example:
DECLARE
ex EXCEPTION;
BEGIN
IF TO_CHAR(SYSDATE,'DY')=='SUN' THEN
RAISE ex;
END IF;
EXCEPTION
WHEN ex THEN
DBMS_OUTPUT.PUT_LINE('No Transactions Today');
END;
/

Database Management System (DMS) Mr. S. Y. Divekar


Topic:- 4.4 : Outlines
Cursors:
Implicit and Explicit cursors,
Declaring, Opening and closing a cursor,
Fetching a record from cursor,
Cursor for loops,
Parameterized cursors.

Database Management System (DMS) Mr. S. Y. Divekar


Cursors:
A cursor is a temporary work area created in the system memory
when a SQL statement is executed.
A cursor contains information on a select statement and the rows
of data accessed by it.
This temporary work area is used to store the data retrieved from
the database, and manipulate this data.
A cursor can hold more than one row, but can process only one
row at a time.
The set of rows the cursor holds is called the active set.
There are two types of cursors in PL/SQL :
1. Implicit cursors.
2. Explicit cursors.

Database Management System (DMS) Mr. S. Y. Divekar


Implicit cursors :
These are created by default when DML statements like, INSERT,
UPDATE, and DELETE statements are executed. They are also
created when a SELECT statement that returns just one row is
executed.
When you execute DML statements like DELETE, INSERT, UPDATE
and SELECT statements, implicit statements are created to
process these statements.
Oracle provides few attributes called as implicit cursor attributes
to check the status of DML operations. The cursor attributes
available are %FOUND, %NOTFOUND, %ROWCOUNT, and
%ISOPEN.

Database Management System (DMS) Mr. S. Y. Divekar


Cursors:

Database Management System (DMS) Mr. S. Y. Divekar


Implicit cursors :
For example, When you execute INSERT, UPDATE, or DELETE
statements the cursor attributes tell us whether any rows are
affected and how many have been affected.
When a SELECT... INTO statement is executed in a PL/SQL Block,
implicit cursor attributes can be used to find out whether any row
has been returned by the SELECT statement. PL/SQL returns an
error when no data is selected.

Database Management System (DMS) Mr. S. Y. Divekar


Implicit cursors :
Consider the PL/SQL Stock that uses implicit cursor attributes as
shown below:
Example:
DECLARE
Eid number(3);
BEGIN
UPDATE emp set eid=&eid where salary=&salary;
eid:=sql%rowcount;
IF SQL%found then
dbms_output.put_line('success');
ELSE
dbms_output.put_line ( ' not' ) ;
END IF;
dbms_output.put_line( 'rowcount'||eid);
END;
/
Database Management System (DMS) Mr. S. Y. Divekar
Explicit Cursors :
They must be created when you are executing a SELECT
statement that returns more than one row.
Even though the cursor stores multiple records, only one record
can be processed at a time, which is called as current row.
When you fetch a row the current row position moves to next
row. An explicit cursor is defined in the declaration section of the
PL/SQL Block.
It is created on a SELECT Statement which returns more than one
row. We can provide a suitable name for the cursor.
Syntax:
CURSOR cursor_name IS select_statement;

cursor _name -A suitable name for the cursor.


Select_statement - A select query which returns multiple rows.

Database Management System (DMS) Mr. S. Y. Divekar


How to use Explicit Cursors :
There are four steps in using an Explicit Cursor.
DECLARE the cursor in the declaration section
OPEN the cursor in the Execution Section.
FETCH the data from cursor into PL/SQL variables or records in
the Execution Section.
CLOSE the cursor in the Execution Section before you end the
PL/SQL Block.
Declaring a Cursor in the Declaration Section:
Syntax:
CURSOR CURSORNAME IS SELECT.......;

Database Management System (DMS) Mr. S. Y. Divekar


How to access an Explicit Cursor:
These are the three steps in accessing the cursor.
 Open the cursor :
Syntax:
OPEN cursor_name;

Fetch the records in the cursor one at a time :


Syntax:
FETCH cursor_name INTO record_name;
OR
FETCH cursor_name INTO variable_list;

Close the cursor:


Syntax:
CLOSE cursor__name;

Database Management System (DMS) Mr. S. Y. Divekar


Explicit Cursor:
Points to remember while fetching a row:
1. We can fetch the rows in a cursor to a PL/SQL Record or a list
of variables created in the PL/SQL Block.
2. If you are fetching a cursor to a PL/SQL Record, the record
should have the same structure as the cursor.
3. If you are fetching a cursor to a list of variables, the variables
should be listed in the same order in the fetch statement as
the columns are present in the cursor.

Database Management System (DMS) Mr. S. Y. Divekar


Explicit Cursor:
General Form of using an explicit cursor is:
Syntax:
DECLARE
variables;
records;
create a cursor;
BEGIN
OPEN cursor;
FETCH cursor;
process the records;
CLOSE cursor;
END;
\

Database Management System (DMS) Mr. S. Y. Divekar


Explicit Cursor:
Example:
DECLARE
CURSOR er IS select eid,name from emp order by name ;
id emp.eid%type;
ename emp.name%type;
BEGIN
OPEN er;
Loop
FETCH er into id,ename;
Exit when er%notfound;
dbms_output.put_line (id || ename);
end loop;
close er;
END;
\
Database Management System (DMS) Mr. S. Y. Divekar
Explicit Cursor:
 Cursor For Loop :
Oracle provides another loop-statements to control loops
specifically for cursors.
This statements is a variation of the basic FOR loop , and it is
known as cursor for loops.
Syntax:
FOR VARIABLE IN CURSORNAME
LOOP
<EXECUTE COMMANDS>
END LOOP

Database Management System (DMS) Mr. S. Y. Divekar


Explicit Cursor:
 Parameterized Cursors :
Oracle allows to pass parameters to cursors that can be used to
provide condition with WHERE clause.
If parameters are passed to cursor, that cursor is called
a parameterized cursors.
Syntax:
CURSOR CURSORNAME (VARIABLENAME DATATYPES ) IS
SELECT.........
And, parameters canbe passed to cursor while opening it using
syntax-
Syntax:
OPEN CURSORNAME (VALUE / VARIABLE / EXPRESSION );

Database Management System (DMS) Mr. S. Y. Divekar


Topic:- 4.5 : Outlines
Procedures:
Advantages,
Creating, Executing and Deleting a Stored procedure

Database Management System (DMS) Mr. S. Y. Divekar


Procedures:
A procedure is a named PL/SQL block which performs one or
more specific task. This is similar to a procedure in other
programming languages. A procedure has a header and a body.
The header consists of the name of the procedure and the
parameters or variables passed to the procedure.
The body consists or declaration section, execution section and
exception section similar to a general PL/SQL Block. A procedure
is similar to an anonymous PL/SQL Block but it is named for
repeated usage.
We can pass parameters to procedures in three ways :

Database Management System (DMS) Mr. S. Y. Divekar


Advantages of Procedures:
• Better Performance –
The procedure calls are quick and efficient as stored procedures are compiled once
and stored in executable form. Hence the response is quick. The executable code is
automatically cached, hence lowers the memory requirements.
•Higher Productivity –
Since the same piece of code is used again and again so, it results in higher
productivity.
•Ease of Use –
To create a stored procedure, one can use any Java Integrated Development
Environment (IDE). Then, they can be deployed on any tier of network architecture.
•Scalability –
Stored procedures increase scalability by isolating application processing on the
server.
•Maintainability –
Maintaining a procedure on a server is much easier then maintaining copies on
various client machines, this is because scripts are in one location.
•Security –
Access to the Oracle data can be restricted by allowing users to manipulate the
data only through stored procedures that execute with their definer’s privileges.

Database Management System (DMS) Mr. S. Y. Divekar


Procedures:
Syntax:
CREATE [OR REPLACE] PROCEDURE procedure_name
(<Argument> {IN, OUT, IN OUT} <Datatype>,…)
IS
Declaration section<variable, constant> ;
BEGIN
Execution section
EXCEPTION
Exception section
END
IS - marks the beginning of the body of the procedure and is similar to
DECLARE in anonymous PL/SQL Blocks. The code between IS and BEGIN forms
the Declaration section.
The syntax within the brackets [ ] indicate they are optional. By using CREATE
OR REPLACE together the procedure is created if no other procedure with the
same name exists or the existing procedure is replaced with the current code.

Database Management System (DMS) Mr. S. Y. Divekar


Procedures:
How to execute a Procedure
There are two ways to execute a procedure
From the SQL prompt : EXECUTE [or EXEC] procedure_name;
Within another procedure – simply use the procedure name :
procedure_name;
Example:
create table named emp have two column id and salary with number datatype.
CREATE OR REPLACE PROCEDURE p1(id IN NUMBER, sal IN NUMBER)
AS
BEGIN
INSERT INTO emp VALUES(id, sal);
DBMD_OUTPUT.PUT_LINE('VALUE INSERTED.');
END;
/

Database Management System (DMS) Mr. S. Y. Divekar


DROP PROCEDURE:
Syntax:
DROP PROCEDURE PROCEDURE_NAME;

Example:
DROP PROCEDURE p1;

Database Management System (DMS) Mr. S. Y. Divekar


Topic:- 4.6 : Outlines
Functions:
Advantages,
Creating, Executing and Deleting a Functions.

Database Management System (DMS) Mr. S. Y. Divekar


Functions:
A function is a named PL/SQL Block which is similar to a
procedure. The major difference between a procedure and a
function is, a function must always return a value, but a
procedure may or may not return a value.
Advantages of Functions :
•We can make a single call to the database to run a block of
statements thus it improves the performance against running SQL
multiple times. This will reduce the number of calls between the
database and the application.
•We can divide the overall work into small modules which becomes
quite manageable also enhancing the readability of the code.
•It promotes reusability.
•It is secure since the code stays inside the database thus hiding
internal database details from the application(user). The user only
makes a call to the PL/SQL functions. Hence security and data hiding
is ensured.

Database Management System (DMS) Mr. S. Y. Divekar


Functions:
Syntax:
CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype; {IS, AS}
Declaration_section <variable,constant> ;
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;

Database Management System (DMS) Mr. S. Y. Divekar


Functions:
RETURN TYPE: The header section defines the return type of the
function.
The return datatype can be any of the oracle datatype like
varchar, number etc.
The execution and exception section both should return a value
which is of the datatype defined in the header section.
How to execute a Function:
A function can be executed in the following ways.
As a part of a SELECT statement
: SELECT emp_details_func FROM dual;
In a PL/SQL Statements like,
: dbms_output.put_line(emp_details_func);
This line displays the value returned by the function .

Database Management System (DMS) Mr. S. Y. Divekar


Functions:
Example:
CREATE [OR REPLACE] FUNCTION getsal (no IN number)
RETURN number
IS
sal number(5);
BEGIN
select salary into sal from emp where id=no;
Return sal;
END;
/

Database Management System (DMS) Mr. S. Y. Divekar


DROP Functions:
Syntax:
DROP FUNCTION FUNCTION_NAME;

Example:
DROP FUNCTION getsal;

Database Management System (DMS) Mr. S. Y. Divekar


Topic:- 4.7 : Outlines
Database Triggers:
Use of Database Triggers,
How to apply database Trigger,
Types of Triggers,
Syntax for Creating Trigger, Deleting Trigger.

Database Management System (DMS) Mr. S. Y. Divekar


Database Triggers:
A trigger is a pl/sql block structure which is fired when a DML
statements like Insert, Delete, Update is executed on a database
table. A trigger is triggered automatically when an associated
DML statement is executed.
Syntax:
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)
BEGIN
--- sql statements
END;
Database Management System (DMS) Mr. S. Y. Divekar
Database Triggers:Each statements are described below :

Database Management System (DMS) Mr. S. Y. Divekar


Database Triggers:
Example:
Create or replace Trigger np before insert on account for each row
Begin
IF :NEW.bal < 0 THEN
DBMS_OUTPUT.PUT_LINE('BALANCE IS NAGATIVE..');
END IF;
End;
/

Database Management System (DMS) Mr. S. Y. Divekar


Use of Database Triggers:
Triggers supplement the standard capabilities of Oracle to
provide a highly customized database management system.

For example, a trigger can permit DML operations against a table


only if they are issued during regular business hours. The
standard security features of Oracle, roles and privileges, govern
which users can submit DML statements against the table. In
addition, the trigger further restricts DML operations to occur
only at certain times during weekdays. This is just one way that
you can use triggers to customize information management in an
Oracle database.

Database Management System (DMS) Mr. S. Y. Divekar


Use of Database Triggers:
In addition, triggers are commonly used to
oautomatically generate derived column values
oprevent invalid transactions
oenforce complex security authorizations
oenforce referential integrity across nodes in a distributed
database
oenforce complex business rules
oprovide transparent event logging
oprovide sophisticated auditing
omaintain synchronous table replicates
ogather statistics on table access

Database Management System (DMS) Mr. S. Y. Divekar


Types of Triggers:
A trigger's type is defined by the type of triggering transaction
and by the level at which the trigger is executed. Oracle has the
following types of triggers depending on the different
applications.
Row Level Triggers
Statement Level Triggers
Before Triggers
After Triggers

Database Management System (DMS) Mr. S. Y. Divekar


Types of Triggers: Row Level Triggers :
Row level triggers execute once for each row in a transaction.
The commands of row level triggers are executed on all rows that
are affected by the command that enables the trigger.
For example, if an UPDATE statement updates multiple rows of a
table, a row trigger is fired once for each row affected by the
UPDATE statement.
If the triggering statement affects no rows, the trigger is not
executed at all. Row level triggers are created using the FOR EACH
ROW clause in the CREATE TRIGGER command.
Application:
Consider a case where our requirement is to
prevent updation of empno 100 record cannot be updated,
then whenever UPDATE statement update records, there must be
PL/SQL block that will be fired automatically by UPDATE
statement to check that it must not be 100, so we have to use
Row level Triggers for that type of applications.

Database Management System (DMS) Mr. S. Y. Divekar


Types of Triggers: Statement Level Triggers :
Statement level triggers are triggered only once for each
transaction.
For example when an UPDATE command update 15 rows, the
commands contained in the trigger are
executed only once, and not with every processed row.
Statement level trigger are the default types of trigger created via
the CREATE TRIGGER command.
Application:
Consider a case where our requirement is to prevent
the DELETE operation during Sunday. For this whenever DELETE
statement deletes records, there must be PL/SQL block that will
be fired only once by DELETE statement to check that day must
not be Sunday by referencing system date, so we have to use
Statement level Trigger for which fires only once for above
application.

Database Management System (DMS) Mr. S. Y. Divekar


Types of Triggers: Before Trigger :
Since triggers are executed by events, they may be set to occur
immediately before or after those events.
When a trigger is defined, you can specify whether the trigger
must occur before or after the triggering event i.e. INSERT,
UPDATE, or DELETE commands.
BEFORE trigger execute the trigger action before the triggering
statement.
These types of triggers are commonly used in the following situation:
1. BEFORE triggers are used when the trigger action should determine
whether or not the triggering statement should be allowed to
complete.
2. By using a BEFORE trigger, you can eliminate unnecessary processing
of the triggering statement.
3. For example: To prevent deletion on Sunday, for this we have to use
Statement level before trigger on DELETE statement.
4. BEFORE triggers are used to derive specific column values before
completing a triggering INSERT or UPDATE statement.

Database Management System (DMS) Mr. S. Y. Divekar


Types of Triggers: After Trigger :
AFTER trigger executes the trigger action after the triggering
statement is executed.
AFTER triggers are used when you want the triggering statement
to complete before executing the trigger action.
For example: To perform cascade delete operation, it means that
user delete the record fro one table, but the corresponding
records in other tables are delete automatically by a trigger which
fired after the execution of delete statement issued by the user.
When combining the different types of triggering actions, there
are mainly 4 possible Valid trigger types available to us.
The possible configurations are:
BEFORE statement Trigger
BEFORE row Trigger
AFTER statement Trigger
AFTER row Trigger

Database Management System (DMS) Mr. S. Y. Divekar


Dropping Triggers:
Triggers may be dropped via the drop trigger command. In order
to drop a trigger, you must either own the trigger or have the
DROP ANY TRIGGER system privilege.
Syntax:
DROP TRIGGER trigger_name;
Example:

Database Management System (DMS) Mr. S. Y. Divekar


Thanks

Database Management System (DMS) Mr. S. Y. Divekar

You might also like