0% found this document useful (0 votes)
5 views50 pages

UNIT V PLSQL

PL/SQL (Procedural Language/Structured Query Language) is a block-structured language developed by Oracle that integrates SQL with procedural programming features for efficient data manipulation. It allows for the creation of reusable units such as procedures, functions, and triggers, and includes error handling capabilities. The document outlines the structure of PL/SQL blocks, variable declaration, assignment operations, and conditional statements, providing examples and explanations for each concept.

Uploaded by

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

UNIT V PLSQL

PL/SQL (Procedural Language/Structured Query Language) is a block-structured language developed by Oracle that integrates SQL with procedural programming features for efficient data manipulation. It allows for the creation of reusable units such as procedures, functions, and triggers, and includes error handling capabilities. The document outlines the structure of PL/SQL blocks, variable declaration, assignment operations, and conditional statements, providing examples and explanations for each concept.

Uploaded by

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

UNIT V

PL/SQL

INTRODUCTION
PL/SQL (Procedural Language/Structured Query Language) is a block-
structured language developed by Oracle that allows developers to combine
the power of SQL with procedural programming constructs.

The PL/SQL language enables efficient data manipulation and control-flow


logic, all within the Oracle Database.

Basics of PL/SQL
 PL/SQL stands for Procedural Language extensions to the
Structured Query Language (SQL).
 PL/SQL is a combination of SQL along with the procedural features
of programming languages.
 Oracle uses a PL/SQL engine to process the PL/SQL statements.
 PL/SQL includes procedural language elements like conditions and
loops. It allows declaration of constants and variables, procedures
and functions, types and variable of those types and triggers.
Features of PL/SQL
1. PL/SQL is basically a procedural language, which provides the
functionality of decision-making, iteration, and many more features
of procedural programming languages.
2. PL/SQL can execute a number of queries in one block using single
command.
3. One can create a PL/SQL unit such as procedures, functions,
packages, triggers, and types, which are stored in the database for
reuse by applications.
4. PL/SQL provides a feature to handle the exception which occurs in
PL/SQL block known as exception handling block.
5. Applications written in PL/SQL are portable to computer hardware
or operating system where Oracle is operational.
6. PL/SQL Offers extensive error checking.
Differences Between SQL and PL/SQL
SQL PL/SQL

SQL is a single query that is used PL/SQL is a block of codes that


to perform DML and DDL used to write the entire program
operations. blocks/ procedure/ function, etc.
SQL PL/SQL

It is declarative, that defines what


PL/SQL is procedural that defines
needs to be done, rather than how
how the things needs to be done.
things need to be done.

Execute as a single statement. Execute as a whole block.

Mainly used to create an


Mainly used to manipulate data.
application.

Cannot contain PL/SQL code in It is an extension of SQL, so it can


it. contain SQL inside it.

Structure of PL/SQL Block

PL/SQL extends SQL by adding constructs found in procedural languages,


resulting in a structural language that is more powerful than SQL. 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.

Typically, each block performs a logical action in the program. A block has
the following structure:
DECLARE
declaration statements;

BEGIN
executable statements
EXCEPTIONS
exception handling statements

END;
 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.
 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.

PL/SQL Identifiers

There are several PL/SQL identifiers such as variables, constants,


procedures, cursors, triggers etc.
1. Variables: Like several other programming languages, variables in
PL/SQL must be declared prior to its use. They should have a valid
name and data type as well.

Syntax for declaration of variables:


variable_name datatype [NOT NULL := value ];

Example to show how to declare variables in PL/SQL :


SQL> SET SERVEROUTPUT ON;

SQL> DECLARE
var1 INTEGER;
var2 REAL;
var3 varchar2(20) ;

BEGIN
null;
END;
/
1. Output:
PL/SQL procedure successfully completed.
1. Explanation:
 SET SERVEROUTPUT ON: It is used to display the buffer
used by the dbms_output.
 var1 INTEGER : It is the declaration of variable,
named var1 which is of integer type. There are many other data
types that can be used like float, int, real, smallint, long etc. It
also supports variables used in SQL as well like
NUMBER(prec, scale), varchar, varchar2 etc.
 PL/SQL procedure successfully completed.: It is displayed
when the code is compiled and executed successfully.
 Slash (/) after END;: The slash (/) tells the SQL*Plus to execute
the block.
 Assignment operator (:=) : It is used to assign a value to a
variable.
2. Displaying Output: The outputs are displayed by using
DBMS_OUTPUT which is a built-in package that enables the user to
display output, debugging information, and send messages from
PL/SQL blocks, subprograms, packages, and triggers. Let us see an
example to see how to display a message using PL/SQL :
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
var varchar2(40) := 'MRCAS' ;

BEGIN
dbms_output.put_line(var);

END;
/
1. Output:
MRCAS

PL/SQL procedure successfully completed.


1. Explanation:
 dbms_output.put_line : This command is used to direct the
PL/SQL output to a screen.
2. Using Comments: Like in many other programming languages, in
PL/SQL also, comments can be put within the code which has no
effect in the code. There are two syntaxes to create comments in
PL/SQL :
 Single Line Comment: To create a single line comment , the
symbol – – is used.
Multi Line Comment: To create comments that span over

several lines, the symbol /* and */ is used.
3. Taking input from user: Just like in other programming languages, in
PL/SQL also, we can take input from the user and store it in a
variable. Let us see an example to show how to take input from users
in PL/SQL:
SQL> SET SERVEROUTPUT ON;

SQL> DECLARE

-- taking input for variable a


a number := &a;

-- taking input for variable b


b varchar2(30) := &b;

BEGIN
null;

END;
/
1. Output:
Enter value for a: 24
old 2: a number := &a;
new 2: a number := 24;
Enter value for b: 'HAI'
old 3: b varchar2(30) := &b;
new 3: b varchar2(30) := 'HAI';

PL/SQL procedure successfully completed.

How to Declare PL/SQL Variables?


When writing PL/SQL code it is important to declare variables properly
to store and manipulate data effectively. Variables act as containers for
values and enable various operations on the stored data.
Variables in PL/SQL are declared using the DECLARE keyword within an
anonymous block or a named program unit such as a procedure, function,
or package.
Common Methods for Declaring Variables in PL/SQL
The below methods are used to declare a variable in PL/SQL are as
follows:
Table of Content
 Using Declare Variables in PL/SQL
 Using Initializing Variables in PL/SQL
 Using Variable Scope in PL/SQL
 Using Variable Attributes
Let's understand each method one be one along with the Examples.
1. Using Declare Variables in PL/SQL
To declare a variable in PL/SQL, use the DECLARE keyword followed by
the variable name and its data type. Optionally, you can also assign an
initial value to the variable using the ':=' operator.
Syntax:
DECLARE
variable_name datatype := initial_value;
here,
 variable_name: It is the name of the variable.
 datatype: It is the data type of the variable.
 := initial_value: It is an optional assignment of an initial value to the
variable.
Example:
DECLARE
name VARCHAR2(20) := 'GeeksForGeeks';
BEGIN
DBMS_OUTPUT.PUT_LINE(name);
END;
Output:

Output
Explanation: In the above Query, We have declares a variable named
"name" with a size of 20 characters and initializes it with the
value GeeksForGeeks then prints the value of the variable
using DBMS_OUTPUT.PUT_LINE.
2. Using Initializing Variables in PL/SQL
In this method Variables can be initialized in two ways either during
declaration or later in the code.
a. Initializing during declaration
Variables can be assigned values when declared, as shown below:
Syntax:
DECLARE
my_variable NUMBER := value;
BEGIN
-- PL/SQL code
END;
Example:
DECLARE
name VARCHAR2(20) := 'GeeksForGeeks';
BEGIN
DBMS_OUTPUT.PUT_LINE(name);
END;
Output:

b. Initialization After Declaration


You can also assign a value to a variable later in the code using the :=
operator.
Syntax:
DECLARE
my_variable NUMBER;
BEGIN
my_variable := value;
END;
Example:
DECLARE
num1 NUMBER;
num2 NUMBER;
result NUMBER;
BEGIN
num1 := 5;
num2 := 3;
result := num1 + num2;
DBMS_OUTPUT.PUT_LINE('Sum: ' || result);
END;
Output:
3. Using Variable Scope in PL/SQL
Variable scope determines where a variable can be accessed within a
program. In PL/SQL, variable scope can be either local or global.
 Local Variables: Declared within a block or subprogram, accessible
only inside that block or subprogram.
 Global Variables: Declared in the outermost block and accessible by
nested blocks.
Example:
DECLARE
global_var NUMBER; -- global variable
BEGIN
-- PL/SQL code using global_var
DECLARE
local_var NUMBER; -- local variable
BEGIN
-- PL/SQL code using local_var and global_var
END;
-- Here you can't access local_var
END;

Explanation: The global_var can be accessed throughout the entire


program, while the local_var is only accessible within the inner block
4. Using Variable Attributes (%TYPE and %ROWTYPE)
PL/SQL provides two powerful attributes, %TYPE and %ROWTYPE,
which allow variables to inherit data types from existing columns or entire
rows.
 %TYPE: It defines a variable with the same data type as another
variable or column.
 %ROWTYPE: It defines a record with the same structure as a table
or cursor.
Example: The below example is demonstrating the use of %TYPE and
%ROWTYPE attribute
Create a employees table and Insert some records into a employees table
-- Creating a employees table
CREATE TABLE employees (
employee_id NUMBER PRIMARY KEY,
first_name VARCHAR2(50),
last_name VARCHAR2(50),
salary NUMBER
);

-- Inserting some records


INSERT INTO employees VALUES (1, 'John', 'Doe', 50000);
INSERT INTO employees VALUES (2, 'Jane', 'Smith', 60000);
INSERT INTO employees VALUES (3, 'Bob', 'Johnson', 55000);
1. Using %TYPE Attribute
In this example, we have declared a variable salary_var using %TYPE to
match the data type of the salary column in the employees table then we
have assigned a value to salary_var and displayed the assigned value
using DBMS_OUTPUT.PUT_LINE.
DECLARE
salary_var employees.salary%TYPE;
BEGIN
-- Assign a value to the variable
salary_var := 70000;

-- Display the assigned value


DBMS_OUTPUT.PUT_LINE('Assigned Salary: ' || salary_var);
END;
Output:
Explanation: In the above Query, We have declares a
variable salary_var with the same data type as the salary column in
the employees table, assigns a value of 70000 to it, and then prints the
assigned salary using DBMS_OUTPUT.PUT_LINE.
2. Using %ROWTYPE Attribute
In this example, We have declared a record
variable employee_record using %ROWTYPE to match the structure of
the employees table and fetched the data from the employees table into
the employee_record variable using a SELECT INTO statement then we
have displayed the retrieved data from
the employee_record using DBMS_OUTPUT.PUT_LINE.
DECLARE
employee_record employees%ROWTYPE;
BEGIN
-- Fetch data from the table into the record variable
SELECT * INTO employee_record FROM employees WHERE
employee_id = 2;

-- Display the retrieved data


DBMS_OUTPUT.PUT_LINE('Employee ID: ' ||
employee_record.employee_id);
DBMS_OUTPUT.PUT_LINE('First Name: ' ||
employee_record.first_name);
DBMS_OUTPUT.PUT_LINE('Last Name: ' ||
employee_record.last_name);
DBMS_OUTPUT.PUT_LINE('Salary: ' || employee_record.salary);
END;
Output:
Explanation: In the above Query, We have declares a record
variable employee_record that matches the structure of
the employees table. It then fetches the data for the employee
with employee_id 2 into the employee_record variable using a SELECT
INTO statement and prints the retrieved data
using DBMS_OUTPUT.PUT_LINE.

ASSIGNMENT OPERATION IN PLSQL

In PL/SQL, := and = serve different purposes:


1. := (Assignment Operator) → Used to assign a value to a variable.
2. = (Comparison Operator) → Used to compare values in SQL
statements (e.g., SELECT, UPDATE, WHERE clause).
Example

DECLARE
v_number NUMBER;
BEGIN
-- Using := for assignment
v_number := 100; -- Correct (Assigning value to variable)

-- Displaying the assigned value


DBMS_OUTPUT.PUT_LINE('Value of v_number: ' || v_number);

-- Using = in SQL statement


IF v_number = 100 THEN -- Correct (Comparison)
DBMS_OUTPUT.PUT_LINE('v_number is 100');
END IF;
END;
/

Incorrect Usage:

DECLARE
v_number NUMBER;
BEGIN
IF v_number := 100 THEN -- Incorrect! := cannot be used for
comparison
DBMS_OUTPUT.PUT_LINE('This will cause an error');
END IF;
END;
/
This will cause an error because := is meant for assignment, not for logical
conditions.

Arithmetic Operators

Following table shows all the arithmetic operators supported by PL/SQL.

For example,
Assume variable A holds 10 and variable B holds 5,

Operato
Description Example
r
+ Adds two operands A + B will give 15

- Subtracts second operand from the first A - B will give 5

* Multiplies both operands A * B will give 50

/ Divides numerator by de-numerator A / B will give 2

Exponentiation operator, raises one operand to the A ** B will give


**
power of other 100000

PL/SQL Conditional Statements


PL/SQL (Procedural Language/Structured Query Language) is an
extension of SQL used in Oracle databases to write procedural code. It
includes various conditional statements that allow developers to execute
different blocks of code based on specific conditions. Decision-making
statements in programming languages decide the direction of the flow of
program execution. Conditional Statements available in PL/SQL are
defined below:
1. IF THEN
2. IF THEN ELSE
3. NESTED-IF-THEN
4. IF THEN ELSIF-THEN-ELSE Ladder
1. IF THEN
if then the statement is the most simple decision-making statement. It is
used to decide whether a certain statement or block of statements will be
executed or not i.e if a certain condition is true then a block of statement is
executed otherwise not.
Syntax:
if condition then
-- do something
end if;
Here, condition after evaluation will be either true or false. if statement
accepts boolean values – if the value is true then it will execute the block of
statements below it otherwise not. if and endif consider as a block here.
Example:
declare
-- declare the values here

begin
if condition then
dbms_output.put_line('output');

end if;

dbms_output.put_line('output2');
end;

-- pl/sql program to illustrate If statement


declare
num1 number:= 10;
num2 number:= 20;

begin

if num1 > num2 then


dbms_output.put_line('num1 small');
end if;

dbms_output.put_line('I am Not in if');

end;
As the condition present in the if statement is false. So, the block below the
if statement is not executed. Output:
I am Not in if
2. IF THEN ELSE
The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won’t. But what if we
want to do something else if the condition is false. Here comes the else
statement. We can use the else statement with if statement to execute a
block of code when the condition is false.
Syntax:-
if (condition) then
-- Executes this block if
-- condition is true
else
-- Executes this block if
-- condition is false

Example:-
-- pl/sql program to illustrate If else statement
declare
num1 number:= 10;
num2 number:= 20;

begin

if num1 < num2 then


dbms_output.put_line('i am in if block');

ELSE
dbms_output.put_line('i am in else Block');
end if;

dbms_output.put_line('i am not in if or else Block');


end;
Output:-
i'm in if Block
i'm not in if and not in else Block
The block of code following the else statement is executed as the condition
present in the if statement is false after calling the statement which is not in
block(without spaces).
3. NESTED-IF-THEN
A nested if-then is an if statement that is the target of another if statement.
Nested if-then statements mean an if statement inside another if statement.
Yes, PL/SQL allows us to nest if statements within if-then statements. i.e,
we can place an if then statement inside another if then statement. Syntax:-
if (condition1) then
-- Executes when condition1 is true
if (condition2) then
-- Executes when condition2 is true
end if;
end if;

-- pl/sql program to illustrate nested If statement


declare
num1 number:= 10;
num2 number:= 20;
num3 number:= 20;

begin
if num1 < num2 then
dbms_output.put_line('num1 small num2');

if num1 < num3 then


dbms_output.put_line('num1 small num3 also');
end if;

end if;

dbms_output.put_line('after end if');


end;
Output:-
num1 small num2
num1 small num3 also
after end if
4. IF THEN ELSIF-THEN-ELSE Ladder
Here, a user can decide among multiple options. The if then statements are
executed from the top down. As soon as one of the conditions controlling
the if is true, the statement associated with that if is executed, and the rest
of the ladder is bypassed. If none of the conditions is true, then the final else
statement will be executed. Syntax:-
if (condition) then
--statement
elsif (condition) then
--statement
.
.
else
--statement
endif
Flow Chart:-

Example:-
-- pl/sql program to illustrate if-then-elif-then-else ladder
declare
num1 number:= 10;
num2 number:= 20;

begin
if num1 < num2 then
dbms_output.put_line('num1 small');

ELSEIF num1 = num2 then


dbms_output.put_line('both equal');

ELSE
dbms_output.put_line('num2 greater');
end if;

dbms_output.put_line('after end if');


end;
Output:-
num1 small
after end if

BASIC LOOP STATEMENT


Basic loop structure encloses sequence of statements in between
the LOOP and END LOOP statements. With each iteration, the sequence
of statements is executed and then control resumes at the top of the loop.
Syntax
The syntax of a basic loop in PL/SQL programming language is −
LOOP
Sequence of statements;
END LOOP;
Here, the sequence of statement(s) may be a single statement or a block of
statements. An EXIT statement or an EXIT WHEN statement is required
to break the loop.
Example
DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
IF x > 50 THEN
exit;
END IF;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line('After Exit x is: ' || x);
END;
/
When the above code is executed at the SQL prompt, it produces the
following result −
10
20
30
40
50
After Exit x is: 60

PL/SQL procedure successfully completed.


You can use the EXIT WHEN statement instead of the EXIT statement −
DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
exit WHEN x > 50;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line('After Exit x is: ' || x);
END;
/
When the above code is executed at the SQL prompt, it produces the
following result −
10
20
30
40
50
After Exit x is: 60

PL/SQL procedure successfully completed.

WHILE LOOP
A WHILE LOOP statement in PL/SQL programming language repeatedly
executes a target statement as long as a given condition is true.
Syntax
WHILE condition LOOP
sequence_of_statements
END LOOP;
Example
DECLARE
a number(2) := 10;
BEGIN
WHILE a < 20 LOOP
dbms_output.put_line('value of a: ' || a);
a := a + 1;
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the
following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

PL/SQL procedure successfully completed.

FOR LOOP

A FOR LOOP is a repetition control structure that allows you to efficiently


write a loop that needs to execute a specific number of times.
Syntax
FOR counter IN initial_value .. final_value LOOP
sequence_of_statements;
END LOOP;
Following is the flow of control in a For Loop −
 The initial step is executed first, and only once. This step allows you
to declare and initialize any loop control variables.
 Next, the condition, i.e., initial_value .. final_value is evaluated. If it is
TRUE, the body of the loop is executed. If it is FALSE, the body of
the loop does not execute and the flow of control jumps to the next
statement just after the for loop.
 After the body of the for loop executes, the value of the counter
variable is increased or decreased.
 The condition is now evaluated again. If it is TRUE, the loop executes
and the process repeats itself (body of loop, then increment step, and
then again condition). After the condition becomes FALSE, the FOR-
LOOP terminates.
Following are some special characteristics of PL/SQL for loop −
 The initial_value and final_value of the loop variable or counter can
be literals, variables, or expressions but must evaluate to numbers.
Otherwise, PL/SQL raises the predefined exception
VALUE_ERROR.
 The initial_value need not be 1; however, the loop counter increment
(or decrement) must be 1.
 PL/SQL allows the determination of the loop range dynamically at
run time.
Example
DECLARE
a number(2);
BEGIN
FOR a in 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the
following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20

PL/SQL procedure successfully completed.

Reverse FOR LOOP Statement


By default, iteration proceeds from the initial value to the final value,
generally upward from the lower bound to the higher bound. You can
reverse this order by using the REVERSE keyword. In such case, iteration
proceeds the other way. After each iteration, the loop counter is
decremented.
However, you must write the range bounds in ascending (not descending)
order. The following program illustrates this −
DECLARE
a number(2) ;
BEGIN
FOR a IN REVERSE 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the
following result −
value of a: 20
value of a: 19
value of a: 18
value of a: 17
value of a: 16
value of a: 15
value of a: 14
value of a: 13
value of a: 12
value of a: 11
value of a: 10

PL/SQL procedure successfully completed.

Nested Blocks

PL/SQL Nested Blocks


Definition
 A nested block is a PL/SQL block written inside another PL/SQL
block.
 Inner blocks can access outer block variables unless shadowed by a
local declaration.

Variable Scope
 Outer block variables are accessible in the inner block unless re-
declared (shadowed).
 Inner block variables are not accessible in the outer block.

PL/SQL Nested Blocks – Variable Scope & Conflicts


1. Without Conflicts (Different Variable Names)
 The inner block can access the outer block variable without issues.

Example

DECLARE
outer_x NUMBER := 10; -- Outer block variable
BEGIN
DBMS_OUTPUT.PUT_LINE('Outer Block x: ' || outer_x);

DECLARE
inner_x NUMBER := 20; -- Inner block variable (different name)
BEGIN
DBMS_OUTPUT.PUT_LINE('Inner Block x: ' || inner_x);
DBMS_OUTPUT.PUT_LINE('Accessing Outer Block x: ' || outer_x);
-- Direct access
END;

DBMS_OUTPUT.PUT_LINE('Outer Block x After Inner Block: ' ||


outer_x);
END;
/
Output:
Outer Block x: 10
Inner Block x: 20
Accessing Outer Block x: 10
Outer Block x After Inner Block: 10

No conflict because the variables have different names.

2. With Conflicts (Same Variable Names)


 The inner block variable shadows the outer variable.
 We need labels to access the outer variable.
Example

DECLARE
x NUMBER := 10; -- Outer block variable
BEGIN
DBMS_OUTPUT.PUT_LINE('Outer Block x: ' || x);

<<outer_block>> -- Label for outer block


DECLARE
x NUMBER := 20; -- Inner block variable (same name, shadows outer
x)
BEGIN
DBMS_OUTPUT.PUT_LINE('Inner Block x: ' || x); -- Refers to inner
x
DBMS_OUTPUT.PUT_LINE('Accessing Outer Block x: ' ||
outer_block.x); -- Using label
END;

DBMS_OUTPUT.PUT_LINE('Outer Block x After Inner Block: ' || x);


END;
/
Output:

Outer Block x: 10
Inner Block x: 20
Accessing Outer Block x: 10
Outer Block x After Inner Block: 10

Inner Block
Case Outer Block Variable Access
Variable
Without Conflicts No conflict, both
Directly accessible
(Different Names) accessible
With Conflicts (Same Shadows outer Use labeled blocks
Name) variable (<<outer_block>>.x)
SQL in PLSQL
PL/SQL allows embedding SQL statements (DML, DDL, and queries)
within its blocks for efficient database interaction.

Data Manipulation
PL/SQL supports INSERT, UPDATE, DELETE, and SELECT statements
within a block.

Example: INSERT, UPDATE, DELETE

DECLARE
v_emp_id NUMBER := 101;
v_salary NUMBER := 50000;
BEGIN
-- Insert a new record
INSERT INTO employees (emp_id, salary) VALUES (v_emp_id,
v_salary);

-- Update salary for the inserted employee


UPDATE employees
SET salary = salary + 5000
WHERE emp_id = v_emp_id;

-- Delete an employee record


DELETE FROM employees WHERE emp_id = v_emp_id;

COMMIT; -- Save changes to the database


END;
/
Explanation

 Use variables to store values dynamically.


 Use COMMIT to save changes.

2. SELECT…INTO – Retrieving Data

To store a single value from SQL into a variable, use SELECT...INTO.

Example: Fetch Employee Name


DECLARE
v_name VARCHAR2(100);
v_emp_id NUMBER := 101;
BEGIN
SELECT emp_name INTO v_name
FROM employees
WHERE emp_id = v_emp_id;

DBMS_OUTPUT.PUT_LINE('Employee Name: ' || v_name);


END;
/

Explanation
 SELECT…INTO is used when fetching one row.
 If no data is found, it raises NO_DATA_FOUND exception.

TCL Statements

TCL (Transaction Control Language) commands manage database


transactions in PL/SQL.
The main TCL commands are:

Command Description
COMMIT Saves all changes permanently
ROLLBACK Undoes changes since last commit
SAVEPOINT Marks a point to which a transaction can be rolled back

1. COMMIT – Saving Changes


 Once COMMIT is executed, changes become permanent.
 Cannot ROLLBACK after COMMIT.
Example: Using COMMIT

BEGIN
INSERT INTO employees (emp_id, emp_name, salary) VALUES (101,
'John', 50000);
UPDATE employees SET salary = 55000 WHERE emp_id = 101;

COMMIT; -- Saves all changes permanently

DBMS_OUTPUT.PUT_LINE('Transaction Committed');
END;
/

Explanation
 Data is saved permanently.
 No rollback is possible after COMMIT.

2. ROLLBACK – Undoing Changes


 ROLLBACK undoes changes since the last COMMIT.
 Useful for handling errors.

Example: Using ROLLBACK

BEGIN
INSERT INTO employees (emp_id, emp_name, salary) VALUES (102,
'Alice', 60000);

-- Simulating an error
ROLLBACK; -- Undo the INSERT operation

DBMS_OUTPUT.PUT_LINE('Transaction Rolled Back');


END;
/
Explanation
 The INSERT operation is undone.
 The database remains unchanged.

3. SAVEPOINT – Partial Rollback


 A SAVEPOINT marks a point within a transaction.
 ROLLBACK TO savepoint_name; rolls back only to that point (not
the entire transaction).

Example: Using SAVEPOINT


BEGIN
INSERT INTO employees (emp_id, emp_name, salary) VALUES (103,
'David', 70000);
SAVEPOINT sp1; -- Savepoint before the next operation

UPDATE employees SET salary = 75000 WHERE emp_id = 103;


SAVEPOINT sp2; -- Another savepoint

DELETE FROM employees WHERE emp_id = 103; -- Deleting the


record

ROLLBACK TO sp2; -- Undo the DELETE, but keep the UPDATE

COMMIT; -- Final commit


DBMS_OUTPUT.PUT_LINE('Transaction Committed After Partial
Rollback');
END;
/

Explanation:
 ROLLBACK TO sp2; undoes only the DELETE but keeps the
UPDATE.
 Final COMMIT saves all remaining changes.

PL/SQL CURSORS AND EXCEPTIONS


Cursors
A cursor is a pointer to this context area. PL/SQL controls the context area
through a cursor. A cursor holds the rows (one or more) returned by a SQL
statement. The set of rows the cursor holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch
and process the rows returned by the SQL statement, one at a time.

There are two types of cursors −


 Implicit cursors
 Explicit cursors

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
1
affected one or more rows or a SELECT INTO statement returned one
or more rows. Otherwise, it returns FALSE.

%NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT,
2 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

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.

If we check the records in customers table, you will find that the rows have
been updated −

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

Explicit Cursors

Explicit cursors are programmer-defined cursors for gaining more control


over the context area. An explicit cursor should be defined in the
declaration section of the PL/SQL Block. It is created on a SELECT
Statement which returns more than one row.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −
 Declaring the cursor for initializing the memory
 Opening the cursor for allocating the memory
 Fetching the cursor for retrieving the data
 Closing the cursor to release the allocated memory
Declaring the Cursor
Declaring the cursor defines the cursor with a name and the associated
SELECT statement.

For example −
CURSOR c_customers IS
SELECT id, name, address FROM customers;

Opening the Cursor


Opening the cursor allocates the memory for the cursor and makes it ready
for fetching the rows returned by the SQL statement into it. For example,
we will open the above defined cursor as follows −
OPEN c_customers;

Fetching the Cursor


Fetching the cursor involves accessing one row at a time. For example, we
will fetch rows from the above-opened cursor as follows −
FETCH c_customers INTO c_id, c_name, c_addr;

Closing the Cursor


Closing the cursor means releasing the allocated memory. For example, we
will close the above-opened cursor as follows −
CLOSE c_customers;

Example
Following is a complete example to illustrate the concepts of explicit
cursors

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.

PL/SQL Cursor FOR LOOP


The PL/SQL FOR LOOP is a construct designed for repetitive execution,
enabling developers to iterate over a specified range of values or through
elements in collections. When used with cursors, the FOR LOOP can
handle the processing of query results efficiently, automatically fetching
rows and iterating over them without requiring explicit OPEN, FETCH,
and CLOSE commands for the cursor

The FOR LOOP in PL/SQL is purpose-built for seamless iteration, whether


traversing a range of values or cycling through collection elements. The
fundamental syntax is elegantly straightforward:

---Standard FOR LOOP


FOR loop_index IN [REVERSE] lower_bound..upper_bound
LOOP
-- Statements to be executed in each iteration
END LOOP;
 loop_index: The loop index or counter variable.
 lower_bound and upper_bound: The range of values for the loop
index.
 REVERSE (optional): Allows looping in reverse order.
Process:
 Initialize the loop index to the lower bound.
 Execute the statements within the loop.
 Increment or decrement the loop index.
 Repeat the process until the loop index reaches the upper bound.

Syntax:
For Standard FOR LOOP:
-- Basic FOR LOOP
FOR loop_index IN lower_bound..upper_bound
LOOP
-- Statements to be executed in each iteration
END LOOP;
For Reverse FOR LOOP:
-- FOR LOOP in Reverse
FOR loop_index IN REVERSE lower_bound..upper_bound
LOOP
-- Statements to be executed in each iteration
END LOOP;

Example of PL/SQL Cursor FOR LOOP


Through two illuminating examples, complete with code snippets and
detailed output explanations, we'll showcase the remarkable versatility of
this construct.
Example 1: Using Cursor FOR LOOP to Print Numbers
This example demonstrates how to print sequential numbers from 1 to 5
using a FOR LOOP.
-- Using FOR LOOP to Print Numbers
DECLARE
-- Loop index
loop_index NUMBER := 1;
BEGIN
FOR loop_index IN 1..5
LOOP
DBMS_OUTPUT.PUT_LINE('Number: ' || loop_index);
END LOOP;
END;
/

Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Explanation: In this example, the FOR LOOP effortlessly prints the


numbers from 1 to 5 using the DBMS_OUTPUT.PUT_LINE statement.
The loop index dynamically changes in each iteration, providing a concise
and readable solution for printing sequential numbers.

FOR UPDATE CLAUSE AND WHERE CURRENT OF CLAUSE

The WHERE CURRENT OF clause is used in some UPDATE and


DELETE statements.

The WHERE CURRENT OF clause in an UPDATE or DELETE statement


states that the most recent row fetched from the table should be updated or
deleted. We must declare the cursor with the FOR UPDATE clause to use
this feature.

Inside a cursor loop, WHERE CURRENT OF allows the current row to be


directly updated.

When the session opens a cursor with the FOR UPDATE clause, all rows in
the return set will hold row-level exclusive locks. Other sessions can only
query the rows, but they cannot update, delete, or select with FOR
UPDATE.
Oracle provides the FOR UPDATE clause in SQL syntax to allow the
developer to lock a set of Oracle rows for the duration of a transaction.

The syntax of using the WHERE CURRENT OF clause in UPDATE and


DELETE statements follows:

WHERE [CURRENT OF cursor_name | search_condition]


Updatable Cursor
Updatable cursors are used to perform manipulation operations such
as deleting, inserting, and updating rows.

FOR UPDATE keyword is used in cursor declaration. Updation can be


performed with FOR UPDATE and FOR UPDATE OF
keyword. FOR UPDATE locks the selected row so another transaction
can't access it.FOR UPDATE OF is used to provide the column for which
the row should be locked.

Syntax:

SET SERVEROUTPUT ON;


DECLARE
--declare variables and cursor;
CURSOR cursor_name IS SELECT statement FROM FOR UPDATE;
BEGIN
OPEN cursor_name;
FETCH cursor_name;
-- to update
UPDATE table_name
CLOSE cursor_name;
--to commit the changes
COMMIT;
END;
/
Examples of PL/SQL Updatable Cursors

DECLARE
CURSOR emp_cur IS
SELECT empno, sal
FROM emp
WHERE deptno = 10
FOR UPDATE; -- This locks the selected rows

v_empno emp.empno%TYPE;
v_sal emp.sal%TYPE;
BEGIN
OPEN emp_cur;

LOOP
FETCH emp_cur INTO v_empno, v_sal;
EXIT WHEN emp_cur%NOTFOUND;

-- Increase salary by 500 for each employee


UPDATE emp
SET sal = v_sal + 500
WHERE CURRENT OF emp_cur;

END LOOP;

CLOSE emp_cur;

COMMIT;

DBMS_OUTPUT.PUT_LINE('Salaries updated successfully for dept


10.');
END;

Example for where current of clause

WHERE CURRENT OF is used with an explicit cursor FOR UPDATE to


update the current row being fetched.

DECLARE
CURSOR emp_cur IS
SELECT empno, sal FROM emp
WHERE deptno = 10
FOR UPDATE;

v_sal emp.sal%TYPE;
v_empno emp.empno%TYPE;
BEGIN
OPEN emp_cur;
LOOP
FETCH emp_cur INTO v_empno, v_sal;
EXIT WHEN emp_cur%NOTFOUND;

-- Increase salary by 500


UPDATE emp
SET sal = v_sal + 500
WHERE CURRENT OF emp_cur;

END LOOP;
CLOSE emp_cur;

DBMS_OUTPUT.PUT_LINE('Salaries updated using WHERE


CURRENT OF.');
END;

PL/SQL Cursors with Parameters


 The cursor can be declared with the parameter or without the
parameter.

 It can have any number of parameters as per requirement.

 Cursors with Parameters are used to work with particular data.

 Parameters are used to create reusable and adaptable code. Explicit


cursors may be declared with parameters.

 The parameter contains a variable and its datatype.

The parameter can have a default value associated with a variable.


Syntax:
DECLARE
declare variables;
--create a cursor with parameter;
BEGIN OPEN cursor;
FETCH cursor;
-- process the rows
CLOSE cursor;
END;

Example of a Parameterized Cursor

GFG cursor is initialized with a parameter to retrieve the Id, name, and
rank of Geek from the Geeks Table. The requested data must satisfy the
specified condition.
SET SERVEROUTPUT ON;
DECLARE
CURSOR GFG (Min_rank NUMBER) IS
SELECT Id, name, rank
FROM Geeks
WHERE rank > Min_rank;
-- Declare variables
cur_id Geeks.Id%TYPE;
cur_name Geeks.name%TYPE;
cur_rank Geeks.rank%TYPE;
BEGIN
-- Open and fetch data using the cursor
OPEN GFG(951);
LOOP
FETCH GFG INTO cur_id, cur_name, cur_rank;
EXIT WHEN GFG%NOTFOUND;
-- Process fetched data
DBMS_OUTPUT.PUT_LINE('ID: ' || cur_id || ', Name: ' || cur_name ||
', Rank: ' || cur_rank);
-- Close the loop
END LOOP;
-- Close the cursor
CLOSE GFG;
END;
Output:

Cursor with Parameter


Table: Establishing a table named Geeks and adding data to it.

Table
Output:
Output
Explanation:
SET SERVEROUTPUT ON is used to display output from
DBMS_OPTPUT.PUT_LINE. GFG cursor and variables are declared in
the declaration block.

The parameter indicates the minimum required rank.


The BEGIN keyword is used to start the execution of code. The cursor is
opened using the OPEN keyword and data is fetched repeatedly from the
table using the LOOP keyword.

Data from the table is checked against the condition mentioned in the
cursor. DBMS_OUTPUT.PUT_LINE to display the data that satisfies the
condition. END LOOP breaks the loop and the cursor is closed using
the CLOSE keyword. The END keyword is used to end the execution.

PL/SQL Parameterized Cursor with Default Value

Default values can be passed in the parameterized cursor. If default values


are passed in the parameterized cursor in the DECLARE block, the cursor
can be called without argument in the BEGIN block if default values are to
be used. If arguments are mentioned then they overwrite the default value.

Syntax:
DECLARE
declare variables;
create a cursor with default value for parameter;
BEGIN OPEN cursor;
FETCH cursor;
process the rows;
CLOSE cursor;
END;

Example of PL/SQL Parameterized Cursor with Default Value

GFG cursor is initialized with a default value for the parameter to retrieve
the Id, name, and rank of Geek from the Geeks Table. The requested data
must satisfy the specified condition mentioned in the cursor.

SET SERVEROUTPUT ON;


DECLARE
--default value for the parameter
CURSOR GFG (Min_rank NUMBER :=951) IS
SELECT Id, name, rank
FROM Geeks
WHERE rank > Min_rank;
-- Declare variables
cur_id Geeks.Id%TYPE;
cur_name Geeks.name%TYPE;
cur_rank Geeks.rank%TYPE;
BEGIN
DBMS_OUTPUT.PUT_LINE('PL/SQL parameterized cursor with
default value');
-- Open and fetch data using the cursor with no argument
OPEN GFG;
LOOP
FETCH GFG INTO cur_id, cur_name, cur_rank;
EXIT WHEN GFG%NOTFOUND;
-- Process fetched data
DBMS_OUTPUT.PUT_LINE('ID: ' || cur_id || ', Name: ' || cur_name ||
', Rank: ' || cur_rank);
-- Close the loop
END LOOP;
-- Close the cursor
CLOSE GFG;
END;

Output of Parameterized Cursor with Default Value:


Output of Parameterized Cursor with default value

Explanation: The example mentioned is the same as the one used earlier. In
this example, default values are used in the parameterized cursor.
In DECLARE block cursor is defined with default value for the
parameter . The cursor is called without argument in the BEGIN section.
Important Points About PL/SQL Parameterized Cursors
 Explicitly close cursors to free up memory resources.
 Use the %NOTFOUND attribute to exit loops when no more rows are
available.
 PL/SQL Cursors with Parameters allows for specific actions to be taken
based on parameterized cursor outcomes.
 You can adapt the cursor's behavior based on different input values.

PL/SQL Cursor Variable with REF CURSOR

In PL/SQL, Cursor variables, also known as REF CURSORs, provide a


dynamic and flexible means to handle query results. A cursor variable is a
reference to a cursor, which can be opened, fetched, and closed dynamically
at runtime.

Why Use REF CURSOR in PL/SQL?

Cursor variables with REF CURSOR are important in PL/SQL


programming for below reasons:
 Dynamic SQL: They allow the creation and execution of dynamic
SQL queries. This is useful when the structure of the query or the
tables involved is not known at compile time.
 Reusability: Cursor variables can be reused across different parts of
the program reducing code duplication and improving
maintainability.
 Parameter Passing: They can be used to pass query results between
different program units such as stored procedures or functions and
enable more modular and flexible code.
 Data Manipulation: They enable complex data
manipulation operations that may involve multiple queries or data
sources.

What is Cursor Variable with REF CURSOR?

Cursor variables in PL/SQL provide a means to work with


dynamic SQL queries and results. Unlike explicit cursors, cursor variables
allow the definition of a cursor without specifying the SQL
query at compile-time.
This flexibility is particularly useful when dealing with varying queries or
when the query needs to be determined dynamically during runtime. REF
CURSORs, associated with cursor variables enable the retrieval of query
results. The below method helps to understand the Cursor Variable with
REF CURSOR very effectively.

1. Using PL/SQL Cursor Variable with REF CURSOR to Fetch Data


Dynamically

We create a PL/SQL block that utilizes a cursor variable with REF


CURSOR to dynamically fetch and display data from the "employees"
table.
The PL/SQL block should open a cursor for a dynamic query that selects
all columns from the "employees" table, fetch the data into variables for
"employee_id" and "employee_name", and then display each employee's
ID and name using the DBMS_OUTPUT.PUT_LINE function. Finally the
cursor should be closed to release resources.

Query:
-- Sample Data
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
employee_name VARCHAR(50)
);
INSERT INTO employees VALUES (1, 'John Doe');
INSERT INTO employees VALUES (2, 'Jane Smith');

-- PL/SQL Block with Cursor Variable


DECLARE
TYPE ref_cursor_type IS REF CURSOR;
cursor_variable ref_cursor_type;
emp_id employees.employee_id%TYPE;
emp_name employees.employee_name%TYPE;
BEGIN
-- Dynamic Query using Cursor Variable
OPEN cursor_variable FOR 'SELECT * FROM employees';

-- Fetch and Display Data


LOOP
FETCH cursor_variable INTO emp_id, emp_name;
EXIT WHEN cursor_variable%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || emp_id || ', Employee
Name: ' || emp_name);
END LOOP;

-- Close Cursor
CLOSE cursor_variable;
END;
/
Output:
Employee
ID Employee Name

1 John Doe

2 Jane Smith
Explanation:
 The cursor variable cursor_variable is dynamically opened for the
query 'SELECT * FROM employees'.
 The loop fetches and displays the data from the result set.

Exceptions in PL/SQL
An exception is an error condition during a program execution. PL/SQL
supports programmers to catch such conditions using EXCEPTION block
in the program and an appropriate action is taken against the error
condition. There are two types of exceptions −
 System-defined exceptions
 User-defined exceptions

Syntax for Exception Handling


The general syntax for exception handling is as follows. Here you can list
down as many exceptions as you can handle. The default exception will be
handled using WHEN others THEN −

DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;

Example
Let us write a code to illustrate the concept.
We will be using the CUSTOMERS table

DECLARE
c_id customers.id%type := 8;
c_name customerS.Name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);

EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
When the above code is executed at the SQL prompt, it produces the
following result −
No such customer!

PL/SQL procedure successfully completed.

The above program displays the name and address of a customer whose ID
is given. Since there is no customer with ID value 8 in our database, the
program raises the run-time exception NO_DATA_FOUND, which is
captured in the EXCEPTION block.

Raising Exceptions

Exceptions are raised by the database server automatically whenever there


is any internal database error, but exceptions can be raised explicitly by the
programmer by using the command RAISE. Following is the simple syntax
for raising an exception −
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
we can use the above syntax in raising the Oracle standard exception or
any user-defined exception.

User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of
your program. A user-defined exception must be declared and then raised
explicitly, using either a RAISE statement or the
procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.

The syntax for declaring an exception is −

DECLARE
my-exception EXCEPTION;
Example
The following example illustrates the concept. This program asks for a
customer ID, when the user enters an invalid ID, the exception invalid_id is
raised.
DECLARE
c_id customers.id%type := &cc_id;
c_name customerS.Name%type;
c_addr customers.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
END IF;

EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/

When the above code is executed at the SQL prompt, it produces the
following result −
Enter value for cc_id: -6 (let's enter a value -6)
old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
ID must be greater than zero!

PL/SQL procedure successfully completed.

Pre-defined Exceptions

PL/SQL provides many pre-defined exceptions, which are executed when


any database rule is violated by a program.

For example, the predefined exception NO_DATA_FOUND is raised when


a SELECT INTO statement returns no rows.

Just Review the below pre defined exceptions : (any four or five u write in
exam)

The following table lists few of the important pre-defined exceptions −


Oracle
Exception SQLCODE Description
Error

It is raised when a null


ACCESS_INTO_NULL 06530 -6530 object is automatically
assigned a value.

It is raised when none


of the choices in the
WHEN clause of a
CASE_NOT_FOUND 06592 -6592
CASE statement is
selected, and there is
no ELSE clause.

COLLECTION_IS_NUL 06531 -6531 It is raised when a


L program attempts to
apply collection
methods other than
EXISTS to an
uninitialized nested
table or varray, or the
program attempts to
assign values to the
elements of an
uninitialized nested
table or varray.

It is raised when
duplicate values are
DUP_VAL_ON_INDEX 00001 -1 attempted to be stored
in a column with
unique index.

It is raised when
attempts are made to
make a cursor
INVALID_CURSOR 01001 -1001 operation that is not
allowed, such as
closing an unopened
cursor.

It is raised when the


conversion of a
character string into a
INVALID_NUMBER 01722 -1722 number fails because
the string does not
represent a valid
number.

It is raised when a
program attempts to
LOGIN_DENIED 01017 -1017 log on to the database
with an invalid
username or password.

It is raised when a
SELECT INTO
NO_DATA_FOUND 01403 +100
statement returns no
rows.

It is raised when a
database call is issued
NOT_LOGGED_ON 01012 -1012 without being
connected to the
database.

PROGRAM_ERROR 06501 -6501 It is raised when


PL/SQL has an
internal problem.

It is raised when a
cursor fetches value in
ROWTYPE_MISMATCH 06504 -6504 a variable having
incompatible data
type.

It is raised when a
member method is
invoked, but the
SELF_IS_NULL 30625 -30625
instance of the object
type was not
initialized.

It is raised when
PL/SQL ran out of
STORAGE_ERROR 06500 -6500
memory or memory
was corrupted.

It is raised when a
SELECT INTO
TOO_MANY_ROWS 01422 -1422
statement returns
more than one row.

It is raised when an
arithmetic, conversion,
VALUE_ERROR 06502 -6502 truncation, or
sizeconstraint error
occurs.

It is raised when an
attempt is made to
ZERO_DIVIDE 01476 1476
divide a number by
zero.

You might also like