0% found this document useful (0 votes)
3 views11 pages

PLSQL Functions

The document provides an overview of PL/SQL functions, procedures, triggers, and cursors, detailing their structure, creation, and usage. It explains how to create and call functions and procedures, including examples for calculating factorials and retrieving customer data. Additionally, it covers the types of cursors, their actions, and the differences between implicit and explicit cursors in PL/SQL.
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)
3 views11 pages

PLSQL Functions

The document provides an overview of PL/SQL functions, procedures, triggers, and cursors, detailing their structure, creation, and usage. It explains how to create and call functions and procedures, including examples for calculating factorials and retrieving customer data. Additionally, it covers the types of cursors, their actions, and the differences between implicit and explicit cursors in PL/SQL.
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/ 11

PL/SQL FUNCTIONS AND PROCEDURES

PL/SQL functions are reusable blocks of code that can be used to perform specific tasks.
They are similar to procedures but must always return a value.
A function in PL/SQL contains:
 Function Header: The function header includes the function name and an optional
parameter list. It is the first part of the function and specifies the name and parameters.
Function Body: The function body contains the executable statements that implement the
specific logic. It can include declarative statements, executable statements, and exception-
handling statements.
Create Function in PL/SQL
To create a procedure in PL/SQL, use the CREATE FUNCTION statement.
Syntax
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];

Where,
 function-name specifies the name of the function.
 [OR REPLACE] option allows the modification of an existing function.
 The optional parameter list contains name, mode and types of the parameters. IN
represents the value that will be passed from outside and OUT represents the
parameter that will be used to return a value outside of the procedure.
 The function must contain a return statement.
 The RETURN clause specifies the data type you are going to return from the
function.
 function-body contains the executable part.
 The AS keyword is used instead of the IS keyword for creating a standalone function.

Example
create a PL/SQL function to calculate factorial of a number
CREATE OR REPLACE FUNCTION factorial(x NUMBER)
RETURN NUMBER
IS
f NUMBER;
BEGIN
IF x = 0 THEN
f := 1;
ELSE
f := x * factorial(x - 1);
END IF;
RETURN f;
END;
How to Call Function in PL/SQL
To call a function, specify the function name and any required parameters. The function will
execute and return a value.
Example
Here, we call the factorial function which we created earlier.

DECLARE
num NUMBER;
result NUMBER;
BEGIN
num := 5;
result := factorial(num);
DBMS_OUTPUT.PUT_LINE('Factorial of ' || num || ' is ' || result);
END;

Example:

This function returns the total number of CUSTOMERS in the customers’ table.
Select * from customers;

+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
CREATE OR REPLACE FUNCTION totalCustomers
RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;

RETURN total;
END;
/

Calling a Function

DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/

Output

Total no. of Customers: 6

PL/SQL procedure successfully completed.

PL/SQL procedures

PL/SQL procedures are reusable code blocks that perform specific actions or logic within
a database environment.
Procedures in PL/SQL
A PL/SQL procedure is a reusable block of code that contains a specific set of actions or
logic.
The procedure contains two parts:
1. Procedure Header
 The procedure header includes the procedure name and optional parameter list.
 It is the first part of the procedure and specifies the name and parameters
2. Procedure Body
 The procedure body contains the executable statements that implement the specific
business logic.
 It can include declarative statements, executable statements, and exception-handling
statements

Creating a Procedure

A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The


simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −

 CREATE [OR REPLACE] PROCEDURE procedure_name


 [(parameter_name [IN | OUT | IN OUT] type [, ...])]
 {IS | AS}
 BEGIN
 < procedure_body >
 END procedure_name;

Where,
 procedure-name specifies the name of the procedure.
 [OR REPLACE] option allows the modification of an existing procedure.
 The optional parameter list contains name, mode and types of the
parameters. IN represents the value that will be passed from outside and OUT
represents the parameter that will be used to return a value outside of the procedure.
 procedure-body contains the executable part.
 The AS keyword is used instead of the IS keyword for creating a standalone
procedure.

Parameter Modes in PL/SQL Subprograms

The following table lists out the parameter modes in PL/SQL subprograms −

S.No Parameter Mode & Description


IN
An IN parameter lets you pass a value to the subprogram. It is a read-
only parameter. Inside the subprogram, an IN parameter acts like a
constant. It cannot be assigned a value. You can pass a constant, literal,
1
initialized variable, or expression as an IN parameter. You can also
initialize it to a default value; however, in that case, it is omitted from the
subprogram call. It is the default mode of parameter passing.
Parameters are passed by reference.
OUT
An OUT parameter returns a value to the calling program. Inside the
2 subprogram, an OUT parameter acts like a variable. You can change its
value and reference the value after assigning it. The actual parameter
must be variable and it is passed by value.
IN OUT
An IN OUT parameter passes an initial value to a subprogram and returns
an updated value to the caller. It can be assigned a value and the value can
3 be read.
The actual parameter corresponding to an IN OUT formal parameter must
be a variable, not a constant or an expression. Formal parameter must be
assigned a value. Actual parameter is passed by value.

Program to find min of two numbers


DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF; END; BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c); END; /
This example creates a procedure that uses OUT parameters, executes the procedure in an
anonymous block, then displays the OUT values. The procedure takes an employee ID as
input then outputs the salary and job ID for the employee.
Command> CREATE OR REPLACE PROCEDURE get_employee
(p_empid in employees.employee_id%TYPE,
p_sal OUT employees.salary%TYPE,
p_job OUT employees.job_id%TYPE) IS
BEGIN
SELECT salary,job_id
INTO p_sal, p_job
FROM employees
WHERE employee_id = p_empid;
END;
/
TRIGGERS

PL/SQL stands for Procedural Language/ Structured Query Language. It has block structure
programming features.PL/SQL supports SQL queries. It also supports the declaration of the
variables, control statements, Functions, Records, Cursor, Procedure, and Triggers.PL/SQL
contains a declaration section, execution section, and exception-handling section. Declare and
exception handling sections are optional.
Syntax:
CREATE OR REPLACE TRIGGER trigger_name
BEFORE or AFTER or INSTEAD OF //trigger timings
INSERT or UPDATE or DELETE // Operation to be performed
of column_name
on Table_name

FOR EACH ROW


DECLARE
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;

 CREATE [ OR REPLACE ] TRIGGER trigger_name is used to create a trigger or


replace the existing trigger.|
 BEFORE | AFTER | INSTEAD OF specifies trigger timing.
 INSERT | UPDATE | DELETE are the DML operations performed on table or views.
 OF column_name specifies the column that would be updated.
 ON table_name species the table for the operation.
 FOR EACH ROW specify that trigger is executed on each row .
Example

Select * from customers;

+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+

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 ROW
WHEN (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; /
Output
UPDATE customers

SET salary = salary + 500


WHERE id = 2;

Old salary: 1500


New salary: 2000
Salary difference: 500
PL/SQL Cursors
The cursor is used to retrieve data one row at a time from the results set, unlike other SQL
commands that operate on all rows at once.
Cursors update table records in a singleton or row-by-row manner.
The Data that is stored in the Cursor is called the Active Data Set. Oracle DBMS has another
predefined area in the main memory Set, within which the cursors are opened. Hence the size
of the cursor is limited by the size of this pre-defined area.
Cursor Actions
Key actions involved in working with cursors in PL/SQL are:
Declare Cursor: A cursor is declared by defining the SQL statement that returns a result set.
Open: A Cursor is opened and populated by executing the SQL statement defined by the
cursor.
Fetch: When the cursor is opened, rows can be fetched from the cursor one by one or in a
block to perform data manipulation.
Close: After data manipulation, close the cursor explicitly.
Deallocate: Finally, delete the cursor definition and release all the system resources
associated with the cursor.
Types of Cursors in PL/SQL
Cursors are classified depending on the circumstances in which they are opened.
Implicit Cursor: If the Oracle engine opened a cursor for its internal processing it is known as
an Implicit Cursor. It is created “automatically” for the user by Oracle when a query is
executed and is simpler to code.
Explicit Cursor: A Cursor can also be opened for processing data through a PL/SQL block, on
demand. Such a user-defined cursor is known as an Explicit Cursor.
Explicit cursor
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.
Syntax for creating cursor
CURSOR cursor_name IS select_statement;
Where,
cursor_name: A suitable name for the cursor.
select_statement: A select query which returns multiple rows
How to use Explicit Cursor?
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 the 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.
Syntax
DECLARE
variables;
records;
CURSOR cursor_name IS select_statement;
BEGIN
OPEN cursor_name;
LOOP
FETCH cursor_name INTO variables OR records;
EXIT WHEN cursor_name%NOTFOUND;
process the records;
END LOOP;
CLOSE cursor_name;
END;

Example

Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+

DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers; BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers; END; /

When the above code is executed at the SQL prompt, it produces the following result −

1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP

PL/SQL procedure successfully completed.

Implicit Cursors

Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement. Programmers cannot control the implicit
cursors and the information in it.

Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor
is associated with this statement. For INSERT operations, the cursor holds the data that needs
to be inserted. For UPDATE and DELETE operations, the cursor identifies the rows that
would be affected.

In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always
has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The
SQL cursor has additional
attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use with
the FORALL statement. The following table provides the description of the most used
attributes −

S.No Attribute & Description


%FOUND
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected
1
one or more rows or a SELECT INTO statement returned one or more
rows. Otherwise, it returns FALSE.
2 %NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT,
UPDATE, or DELETE statement affected no rows, or a SELECT INTO
statement returned no rows. Otherwise, it returns FALSE.
%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the
SQL cursor automatically after executing its associated SQL statement.
%ROWCOUNT
4 Returns the number of rows affected by an INSERT, UPDATE, or
DELETE statement, or returned by a SELECT INTO statement.

Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the
example.

Example

We will be using the CUSTOMERS table we had created and used in the previous chapters.

Select * from customers;

+----+----------+-----+-----------+----------+
| 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 will update the table and increase the salary of each customer by 500
and use the SQL%ROWCOUNT attribute to determine the number of rows affected −

DECLARE
total_rows number(2); BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF; END; /

When the above code is executed at the SQL prompt, it produces the following result −

6 customers selected
PL/SQL procedure successfully completed.

You might also like