Unit V
Unit V
Unit V
PL/SQL
PL/SQL Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or
more specific tasks. It is just like procedures in other programming languages.
A Procedure is a subprogram unit that consists of a group of PL/SQL statements. Each procedure
in Oracle has its own unique name by which it can be referred. This subprogram unit is stored as
a database object
The procedure contains a header and a body.
Header: The header contains the name of the procedure and the parameters or variables passed
to the procedure.
Body: The body contains a declaration section, execution section and exception section similar
to a general PL/SQL block.
characteristics
• Procedures are standalone blocks of a program that can be stored in the database.
• Call to these procedures can be made by referring to their name, to execute the PL/SQL
statements.
• It is mainly used to execute a process in PL/SQL.
• It can have nested blocks, or it can be defined and nested inside the other blocks or
packages.
• It contains declaration part (optional), execution part, exception handling part (optional).
• The values can be passed into the procedure or fetched from the procedure through
parameters.
• These parameters should be included in the calling statement.
• Procedure can have a RETURN statement to return the control to the calling block, but it
cannot return any values through the RETURN statement.
• Procedures cannot be called directly from SELECT statements. They can be called from
another block or through EXEC keyword.
Parameter:
1 | Page
• The parameter is variable or placeholder of any valid PL/SQL datatype through which the
PL/SQL subprogram exchange the values with the main code. This parameter allows to
give input to the subprograms and to extract from these subprograms.
• These parameters should be defined along with the subprograms at the time of creation.
• These parameters are included n the calling statement of these subprograms to interact
the values with the subprograms.
• The datatype of the parameter in the subprogram and the calling statement should be
same.
• The size of the datatype should not mention at the time of parameter declaration, as the
size is dynamic for this type.
How to pass parameters in procedure:
When you want to create a procedure or function, you have to define parameters.
There is three ways to pass parameters in procedure:
1. IN Parameter
2. OUT Parameter
3. IN OUT Parameter
1. IN Parameter
• This parameter is used for giving input to the subprograms.
• It is a read-only variable inside the subprograms. Their values cannot be changed inside
the subprogram.
• In the calling statement, these parameters can be a variable or a literal value or an
expression, for example, it could be the arithmetic expression like '5*8' or 'a/b' where 'a'
and 'b' are variables.
By default, the parameters are of IN type.
2. OUT Parameter:
• RETURN is the keyword that instructs the compiler to switch the control from the
subprogram to the calling statement. In subprogram RETURN simply means that the
control needs to exit from the subprogram. Once the controller finds RETURN keyword
in the subprogram, the code after this will be skipped.
● Normally, parent or main block will call the subprograms, and then the control will shift
from those parent block to the called subprograms. RETURN in the subprogram will
return the control back to their parent block. In the case of functions RETURN statement
also returns the value. The datatype of this value is always mentioned at the time of
function declaration. The datatype can be of any valid PL/SQL data type.
PL/SQL Create Procedure
Syntax for creating procedure:
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];
Subprogram
3 | Page
End;
Explanation
• CREATE PROCEDURE instructs the compiler to create new procedure.
• Keyword 'OR REPLACE' instructs the compile to replace the existing procedure (if any)
with the current one.
• Procedure name should be unique.
• Keyword 'IS' will be used, when the procedure is nested into some other blocks.
If the procedure is standalone then 'AS' will be used. Other than this coding standard, both have
the same meaning.
Example
The following example creates a simple procedure that displays the string 'Hello World!' on the
screen when executed.
When the above code is executed using the SQL prompt, it will produce the following result
Procedure created.
4 | Page
EXECUTE greetings;
The above call will display
Hello World
PL/SQL procedure successfully completed.
Example 2
Code Explanation:
Code line 1: Creating the procedure with name 'welcome_msg' and with one parameter 'p_name'
of 'IN' type.
Code line 4: Printing the welcome message by concatenating the input name.
Code line 7: Calling the procedure using EXEC command with the parameter 'Guru99'.
Procedure is executed, and the message is printed out as "Welcome Guru99".
In this example, we are going to insert record in user table. So you need to create user table first.
Table creation:
5 | Page
create table user(id number(10) primary key,name varchar2(100));
IN & OUT Mode Example 1
This program 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;
6 | Page
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
This procedure computes the square of value of a passed value. This example shows how we can
use the same parameter to accept a value and then return another result.
When the above code is executed at the SQL prompt, it produces the following result
Square of (23): 529
PL/SQL procedure successfully completed.
PL/SQL Function
The PL/SQL Function is very similar to PL/SQL Procedure.
7 | Page
The main difference between procedure and a function is, a function must always return a value,
and on the other hand a procedure may or may not return a value.
Except this, all the other things of PL/SQL procedure are true for PL/SQL function too.
Characteristics
• Functions are a standalone block that is mainly used for calculation purpose.
• Function use RETURN keyword to return the value, and the datatype of this is defined at
the time of creation.
• A Function should either return a value or raise the exception, i.e. return is mandatory in
functions.
• Function with no DML statements can be directly called in SELECT query whereas the
function with DML operation can only be called from other PL/SQL blocks.
• It can have nested blocks, or it can be defined and nested inside the other blocks or
packages.
• It contains declaration part (optional), execution part, exception handling part (optional).
• The values can be passed into the function or fetched from the procedure through the
parameters.
• These parameters should be included in the calling statement.
• Function can also return the value through OUT parameters other than using RETURN.
• Since it will always return the value, in calling statement it always accompanies with
assignment operator to populate the variables.
8 | Page
Function_name: specifies the name of the function.
[OR REPLACE] option allows modifying an existing function.
The optional parameter list contains name, mode and types of the parameters.
IN represents that value will be passed from outside and OUT represents that this parameter will
be used to return a value outside of the procedure.
9 | Page
PL/SQL function example using table
Let's take a customer table. This example illustrates creating and calling a standalone function.
This function will return the total number of CUSTOMERS in the customers table.
• While creating a function, you have to give a definition of what the function has to do.
• To use a function, you will have to call that function to perform the defined task. Once
the function is called, the program control is transferred to the called function.
• After the successful completion of the defined task, the call function returns program
control back to the main program.
• To call a function you have to pass the required parameters along with function name and
if function returns a value then you can store returned value.
Following program calls the function totalCustomers from an anonymous block:
10 | Page
11 | Page
PL/SQL Composite Data Types:- Records, Tables and Varrays
Eg:
RECORD
TABLE
NESTED TABLE
VARRAY
PL/SQL records
A PL/SQL record is a data structure that can hold data items of different kinds. Records consist
of different fields, similar to a row of a database table.
For example,To keep track of books in a library. we might want to track the following attributes
about each book like, Title, Author, Subject, Book ID. A record containing a field for each of
these items allows treating a BOOK as a logical unit and allows you to organize and represent its
information in a better way.
CURSOR cursorname IS
12 | Page
SELECT query;
Recordname CursorName%ROWTYPE;
DECLARE
TYPE books IS RECORD(title varchar(50), author varchar(50), subject varchar(100),
book_id number);
book1 books;
book2 books;
Referencing Fields in a Record
Fields can be referenced by using record name as qualifier.
Recordname.fieldname
Eg: Books.title
DECLARE
type books is record
(title varchar2(50),
author varchar2(50),
subject varchar2(100),
book_id number);
book1 books;
book2 books;
BEGIN -- Book 1 specification
13 | Page
book1.title := 'C Programming';
book1.author := 'Nuha Ali ';
book1.subject := 'C Programming Tutorial';
book1.book_id := 6495407;
-- Book 2 specification
book2.title := 'Telecom Billing';
book2.author := 'Zara Ali';
book2.subject := 'Telecom Billing Tutorial';
book2.book_id := 6495700;
End;
/
When the above code is executed at SQL prompt, it produces the following result:
14 | Page
Nested Records
We can create nested record by including a record into another record as a field. The record that
contains another record as a field is called the enclosing record
. Eg:
DECLARE
TYPE address_rectype IS RECORD
(first VARCHAR2(10),
Last VARCHAR2(10),
Street VARCHAR2(10),
City VARCHAR2(10),
State VARCHAR2(10));
TYPE ALL_ADDRESS_RECTYPE IS RECORD
(HOME_ADDRESS ADDRESS_RECTYPE,
BUS_ADDRESS ADDRESS_RECTYPE,
VACATION_ADDRESS ADDRESS_RECTYPE);
ADDRESS_REC ALL_ADDRESS_RECTYPE;
15 | Page
PL/SQL TABLES/ Associate Array
Nesting records makes code more readable and easier to maintain. We Dot notation is also used
to reference fields in the nested situation.
TPL/SQL tables help you move bulk data. They can store columns or rows of Oracle data, and
they can be passed as parameters. So, PL/SQL tables make it easy to move collections of data
into and out of database tables or between client-side applications and stored subprograms.
The rows in a table are referenced in the same way that an element in an array is referenced. We
must use the primary key values in a pair of parentheses as its subscript or index.
Tablename(primarykeyvalue)
Assigning values to rows in a PL/SQL Table
We can assign values to the rows in a table in three ways:
Direct assignment
Assignment in a loop
16 | Page
Aggregate assignment
Direct assignment
We can assign a value to a row with an assignment. This is preferable if only a few assignments
are to be made.
Assignment in a loop
We can use any of the three PL/SQL loops to assign values to rows in a table.
Aggregate assignment
PL/SQL VARRAYS
17 | Page
• Declare a PL/SQL VARRAY type with a TYPE statement. The TYPE declaration
includes a size to set the upper bound of a varray. The lower bound is always one.
• Declare an actual varray based on the type declared in the previous step.
A varray is another composite data type or collection type in PL/SQL.
Variable-size array – single dimensional array- collection of elements with the same data type.
VARRAY declaration is done in two steps
• Declare a PL/SQL VARRAY type with a TYPE statement. The TYPE declaration
includes a size to set the upper bound of a varray. The lower bound is always one.
• Declare an actual varray based on the type declared in the previous step.
VARRAYS syntax
18 | Page
Student: Kavita
Marks: 98
Student: Pritam
Marks: 97
Student: Ayan
Marks: 78
Student: Rishav
Marks: 87
Student: Aziz
Marks: 92
19 | Page
a number(2):=23;
b number(2):=2;
Begin
Add(a,b);-----calling procedure
End;
Sub program==== add() )---called procedure
Create procedure add(x in number, y in number)
is
Begin
Dbms_output.put_line(x || y); output
23 2
End;
Sample query for record
Declare
Type ss is record( a number(3), b varchar2(12))
x1 ss;
X2 ss;
X3 ss;
Begin
X1.a=22;
X1.b=‘arun’;
X2.a=33;
X2.b=‘brindha’;
X3.a=44
X3.b=‘chandru’;
Dbms_output.put_line(x1.a);
Dbms_output.put_line(x1.b);
Dbms_output.put_line(x2.a);
Dbms_output.put_line(x2.b);
Dbms_output.put_line(x3.a);
Dbms_output.put_line(x3.b);
End;
Output:
22
Arun
33
Brindha
44
Chandru
A package is a way of logically storing the subprograms like procedure, function, exception or
cursor into a single common unit. A package can be defined as an oracle object that is compiled
.and stored in the database
Once it is compiled and stored in the database it can be used by all the users of database who
.have executable permissions on Oracle database
Components of Package
Package has two basic components:
Specification: It is the declaration section of a Package
Body: It is the definition section of a Package.
1. Package specification or declaration
It mainly comprises of the following:
1. Package Name.
2. Variable/constant/cursor/procedure/function/exception declaration.
3. This declaration is global to the package.
Syntax
21 | Page
• where,
• FUNCTION and PROCEDURE are keywords used to declare function and procedure
Example:
22 | Page
CREATE PACKAGE cust_sal AS
PROCEDURE find_sal(c_id customers.id%type);
END cust_sal;
/
When the above code is executed at SQL prompt, it produces the following result:
Package created.
Package Body
It contains the definition of procedure, function or cursor that is declared in the package
specification.
It contains the subprogram bodies containing executable statements for which package
syntax:
CREATE OR REPLACE PACKAGE BODY are keywords used to create the package
with a body.
FUNCTION and PROCEDURE are keywords used to define function and procedure
while creating package.
<package_name>, <function_name>, <procedure_name> are user-defined.
IS/AS are keywords used to define the body of package, function and procedure.
RETURN is a keyword specifying value returned by the function defined.
DECLARE, BEGIN, EXCEPTION, END are the different sections of PL/SQL code
block containing variable declaration,
executable statements, error handling statements and marking end of PL/SQL block
respectively where DECLARE and EXCEPTION part are optional.
Following is the syntax for referring a package object:
Packagename.objectname;
The Object can be a function, procedure, cursor, exception that has been declared in the
package specification and defined in the package body and to access their executable
statements above syntax is used.
23 | Page
The CREATE PACKAGE BODY Statement is used for creating the package body.
The following code snippet shows the package body declaration for the cust_sal package
created above.
Package Body
24 | Page
Enter value for cc_id: 1
Salary: 3000
PL/SQL procedure successfully completed.
Example
write a simple program to demonstrate the use of Package in PL/SQL.
PL/SQL code for package specification:
25 | Page
PL/SQL code for package body:
write the PL/SQL code for calling the Procedure and Function used in Package.
:
Output:
Enter value for sno: 12
Enter value for snm: Neha
RECORD UPDATED
RECORD NOT FOUND
If the package specification or package body has been created with compilation errors
then a following warning message is displayed on the screen:
26 | Page
Package Specification
Create Package specification code for defining procedure, function IN or OUT parameter
Package Body
Create Package body code for implementing procedure or function that are defined
package specification. Once you implement execute this program.
CREATE PACKAGE BODY pkg1
IS
PROCEDURE pro1(no in number, info out varchar2)
IS
BEGIN
SELECT * INTO temp FROM emp1 WHERE eno = no;
END;
FUNCTION fun1(no in number) return varchar2
IS
name varchar2(20);
27 | Page
BEGIN
SELECT ename INTO name FROM emp1 WHERE eno = no;
RETURN name;
END;
END;
/
Pl/SQL Program calling Package (main program)
Now we have a one package pkg1, to call package defined function, procedures also pass
the parameter and get the return result.
Result
Now execute the above created pkg_prg.sql program to asking which user information
you want to get, you put user id and give information.
no number &n=2
Procedure Result
2 marks jems Program Developer 38K
Function Result
marks jems
28 | Page
PL/SQL procedure successfully completed.
Sample query
1.Package specification
2. Package body
3. Main program
1.Package specification
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 could be defined on the table, view, schema, or database with which the event is
associated.
Trigger is invoked by Oracle engine automatically whenever a specified event occurs.
Trigger is stored into database and invoked repeatedly, when specific condition match.
Triggers are stored programs, which are automatically executed or fired when some event
occurs.
Syntax Explanation:
29 | Page
The above syntax shows the different optional statements that are present in trigger creation.
30 | Page
Example:
To start with, we will be using the CUSTOMERS table we had created and used in the previous
chapters:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
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 CUSTOMERS 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 customers
FOR EACH ROWWHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
When the above code is executed at SQL prompt, it produces the following result:
Trigger created.
Here following two points are important and should be noted carefully:
31 | Page
● OLD and NEW references are not available for table level triggers, rather you can use
● 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.
● 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 DELETE operation on the table.
Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT
statement, which will create a new record in the table:
32 | Page
Output: trigger created
After initializing the trigger CheckAge, whenever we will insert any new values or update the
existing values in the above table STUDENT our trigger will check the age before
executing INSERT or UPDATE statements and according to the result of triggering restriction or
condition it will execute the statement.
33 | Page
34 | Page