0% found this document useful (0 votes)
6 views

Unit-3-PL-SQL

Unit 3 covers Procedural SQL and Exception Handling in PL/SQL, detailing the structure of PL/SQL blocks, including declaration, executable, and exception-handling sections. It discusses user-defined data types, control statements, and exception management, along with the advantages and disadvantages of PL/SQL. Additionally, it provides examples of variable usage, control structures like IF...THEN and loops, and highlights the differences between SQL and PL/SQL.

Uploaded by

pandyaj036
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit-3-PL-SQL

Unit 3 covers Procedural SQL and Exception Handling in PL/SQL, detailing the structure of PL/SQL blocks, including declaration, executable, and exception-handling sections. It discusses user-defined data types, control statements, and exception management, along with the advantages and disadvantages of PL/SQL. Additionally, it provides examples of variable usage, control structures like IF...THEN and loops, and highlights the differences between SQL and PL/SQL.

Uploaded by

pandyaj036
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Unit 3 Procedural SQL and Exception Handling

3.1. PL/SQL Block Structure


3.1.1. Using Variables, Constants and Data Type
3.1.2. Control Statements :IF…THEN statement, Loop, FOR...Loop, While Loop
3.2. User-Defined RECORD and TABLE data types.
3.3. Exceptions
3.3.1. User defined Exceptions and Pre-defined Exceptions
3.3.2. Handling Exceptions
3.3.3. Raising Exceptions
3.4. Working with Views

3.1. PL/SQL Block Structure

➢ PL/SQL is a block-structured language whose code is


organized into blocks.
➢ A PL/SQL block consists of three sections: declaration,
executable, and exception-handling sections.
➢ In a block, the executable section is mandatory while the
declaration and exception-handling sections are optional.

1) Declaration section
❖ This section declares variables, constants, cursors, and user-defined types.
❖ It begins with the keyword DECLARE.
2) Executable section

❖ A PL/SQL block has an executable section.


❖ An executable section starts with the keyword BEGIN and ends with the keyword
END.
❖ The executable section must have at least one executable statement.
(e.g., NULL; if no other statements are needed).

1 Prepared By:-
Darshana V.Halatwala
3) Exception-handling section

❖ A PL/SQL block has an exception-handling section that starts with


the keyword EXCEPTION.
❖ The exception-handling section is where you catch and handle
exceptions raised by the code in the execution section.

Basic PL/SQL Block Structure Example:


DECLARE
v_name VARCHAR2(50); -- Declaration section
BEGIN
v_name := 'John Doe'; -- Executable section
DBMS_OUTPUT.PUT_LINE('Name: ' || v_name);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred'); -- Exception section
END;

Example user input


DECLARE
v_employee_id NUMBER;
v_employee_name VARCHAR2(100);
v_ph_no NUMBER;
BEGIN
-- Get user input using substitution variables (for tools like SQL*Plus)
v_employee_id :=:emp_no;
v_employee_name :=:ename;

2 Prepared By:-
Darshana V.Halatwala
v_ph_no :=:ph_no;

-- Insert into table


INSERT INTO emp1 (emp_no, ename, ph_no)
VALUES (v_employee_id, v_employee_name, v_ph_no);
DBMS_OUTPUT.PUT_LINE('Employee ' || v_employee_name || ' inserted successfully.');
COMMIT;
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE('Error: Employee ID already exists.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
END;

Advantages of PL/SQL
● 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 a high security level.
● PL/SQL provides access to predefined SQL packages
● PL/SQL provides support for Object-Oriented Programming.
● PL/SQL provides support for developing Web Applications and
Server Pages.

Disadvantages of PL/SQL

● Stored Procedures in PL/SQL uses high memory


● Lacks functionality debugging in stored procedures
● Any change in underlying database requires change in the presentation layer
also
● Does not completely separate roles of back-end developer and front-end
developer

3 Prepared By:-
Darshana V.Halatwala
● Difficult to separate HTML development with PL/SQL development

Sr. Key SQL PL/SQL


No.

1 Definition SQL, is Structural PL/SQL is a programming


Query Language for language using SQL for a
database. database.

2 Variables SQL has no variables. PL/SQL has variables, data


types etc.

3 Control SQL has no FOR loop, PL/SQL has FOR loop, while
Structures if control and similar loop, if controls and other
structures. similar structures.

4 Operations SQL can execute a PL/SQL can perform multiple


single operation at a operations at a time.
time.

Language SQL is a declarative( PL/SQL is a procedural


5
Type what data they want to language.
retrieve from a database)
language.

6 Embedded SQL can be PL/SQL can also be embedded


embedded(a in SQL code.
combination of
computer hardware
and software
designed for a

4 Prepared By:-
Darshana V.Halatwala
specific function) in
a PL/SQL block.

6 Interaction SQL directly interacts PL/SQL does not


with the database directly interact with
server. database servers.

7 Orientation SQL is a data oriented PL/SQL is an application


language. oriented language.

8 Objective SQL is used to write PL/SQL is used to write


queries, create and program blocks, functions,
execute DDL and procedures, triggers and
DML statements. packages.

3.1.1. Using Variables, Constants and Data Type


1)NUMBER(p,s)

Range: p= 1 to 38 s= -84 to 127

This datatype is used to store numeric data. Here, p is precision and s is scale.

Example:

1. Age NUMBER(2); where , Age is a variable that can store 2 digits


2. percentage NUMBER(4,2); where, percentage is a variable that can store 4
(p) digits before decimal and 2 (s) digits after decimal.

2)CHAR(size)
Range: 1 to 2000 bytes
5 Prepared By:-
Darshana V.Halatwala
· This datatype is used to store alphabetical strings of fixed length.
· Its value is quoted in single quotes.
· Occupies the whole declared size of memory even if the space is not utilized
by the data.

Example:

1. rank CHAR(10); where, rank is a variable that can store up to 10


characters. If the length of data(characters) stored in rank is 5 then it will
still occupy all the 10 spaces. 5 spaces in the memory will get used and the
rest of the blank memory spaces will be wasted.

3) VARCHAR(size)

Range: 1 to 2000 bytes

This datatype is used to store alphanumeric strings of variable length.

· Its value is quoted in single quotes.

· Occupies the whole declared size of memory even if the space is not utilized
by the data.

Example:

1. address VARCHAR(10); where, address is a variable that can


occupy a maximum 10 bytes of memory space and can store
alphanumeric value in it. Unused spaces are wasted.

4) VARCHAR2(size)

Range: 1 to 4000 bytes

· This datatype is used to store alphanumeric strings of variable length.

· Its value is quoted in single quotes.

6 Prepared By:-
Darshana V.Halatwala
· It releases the unused space in memory, hence saving the unused space.

Example:

1. name VARCHAR2(10); where name is a variable that can occupy


a maximum 10 bytes of memory to store an alphanumeric value. The
unused memory space is released.

5) DATE

Range: 01-Jan-4712 BC to 31-DEC-9999

It stores the data in date format DD-MN-YYYY

· The value for this data type is written in single quotes.

Example:
1. DOB DATE; where, DOB is a variable that stores date of birth in defined
format (i.e,’13-FEB- 1991’)

6) %TYPE

It stores the value of that variable whose data type is unknown and when we
want the variable to inherit the datatype of the table column.

Also, its value is generally being retrieved from an existing table in the
database, hence it takes the datatype of the column for which it is used.
Syntax:-
<var_name> <tab_name>.<column_name>%TYPE;
Example:
SALARY EMP.SAL % TYPE;

1. Student sno %TYPE;, where Student is the name of the table created in
the database and sno is variable whose data type is unknown and %TYPE
is used to store its value.

7 Prepared By:-
Darshana V.Halatwala
Example

CREATE TABLE employees ( emp_id NUMBER(10), emp_name


VARCHAR2(50), salary NUMBER(10, 2) );

DECLARE

v_emp_id employees.emp_id%TYPE; -- Matches the data type of emp_id

v_emp_name employees.emp_name%TYPE; -- Matches the data type of


emp_name

v_salary employees.salary%TYPE; -- Matches the data type of salary


BEGIN -- Assigning values

v_emp_id := 101;

v_emp_name := 'JohnDoe';

v_salary := 55000.50; -- Output the values

DBMS_OUTPUT.PUT_LINE('Employee ID: ' || v_emp_id);


DBMS_OUTPUT.PUT_LINE('Employee Name: ' || v_emp_name);
DBMS_OUTPUT.PUT_LINE('Salary: ' || v_salary);

END;

7) BOOLEAN

This datatype is used in conditional statements.

· It stores logical values.

· It can be either TRUE or FALSE

Example:

8 Prepared By:-
Darshana V.Halatwala
1. isAdmin BOOLEAN; where, isAdmin is a variable whose
value can be TRUE or FALSE depending upon the condition being
checked.

Variable Declaration in PL/SQL

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.

Example:-
sales number(10, 2);
name varchar2(25);

Initializing Variables in PL/SQL

Whenever you declare a variable, PL/SQL assigns it a default value of NULL. If


you want to initialize a variable with a value other than the NULL value, you can
do so during the declaration, using either of the following −

The DEFAULT keyword

The assignment operator

For example −

counter binary_integer := 0;

greetings varchar2(20) DEFAULT 'Have a Good Day';

EXAMPLE:-

9 Prepared By:-
Darshana V.Halatwala
DECLARE
a integer := 10;
b integer := 20;
c integer;

BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
END;
/
3.1.2. Control Statements :IF…THEN statement, Loop, FOR...Loop, While Loop
if ….then statement
if then 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.
Syantax:-
IF condition
THEN
Statement: {It is executed when condition is true}
END IF;
Example:-
declare
num1 number:= 10;
num2 number:= 20;
begin
if num1 > num2 then
dbms_output.put_line('statement true');
end if;
dbms_output.put_line('I am Not in if');
end;
if – then- else:

10 Prepared By:-
Darshana V.Halatwala
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
{...statements to execute when condition is TRUE...}
ELSE
{...statements to execute when condition is FALSE...}
END IF;

Example:-
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;

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
11 Prepared By:-
Darshana V.Halatwala
THEN
{...statements to execute when condition1 is TRUE...}
ELSIF condition2
THEN
{...statements to execute when condition2 is TRUE...}
END IF;

Example:-
declare
num1 number:= 10;
num2 number:= 20;
num3 number:= 5;
begin
if num1 < num2 then
dbms_output.put_line('num1 small num2');
if num1 < num3 then
dbms_output.put_line('num1 small num3also');
end if;
end if;
dbms_output.put_line('after end if');
End;

More Example of:-


1)Check if a number is positive, negative, or zero
1)DECLARE
v_number NUMBER;
BEGIN
v_number := :Enter_number;
IF v_number > 0 THEN
DBMS_OUTPUT.PUT_LINE('The number ' || v_number || ' is positive.');
ELSIF v_number < 0 THEN
DBMS_OUTPUT.PUT_LINE('The number ' || v_number || ' is negative.');
ELSE
DBMS_OUTPUT.PUT_LINE('The number is zero.');
END IF;
END; /

12 Prepared By:-
Darshana V.Halatwala
2. Check if a user is eligible to vote
DECLARE
v_age NUMBER;
BEGIN
v_age :=: your_age;
IF v_age >= 18 THEN
DBMS_OUTPUT.PUT_LINE('You are eligible to vote.');
ELSE DBMS_OUTPUT.PUT_LINE('You are not eligible to vote.');
END IF;
END; /

Loops:-
Loops in PL/SQL provides a way of repeating a particular part of any
program or any code statement as many times as required.

In PL/SQL we have three different loop options to choose from when


we want to execute a statement repeatedly in our code block. They
are:
➢ Basic Loop
➢ While Loop
➢ For Loop

1) Basic Loop

Basic loop structure encloses a 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
13 Prepared By:-
Darshana V.Halatwala
The syntax of a basic loop in PL/SQL programming language is −

LOOP

Sequence of statements;

END 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;
/
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;

14 Prepared By:-
Darshana V.Halatwala
/
2) 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;
/
PL/SQL block that calculates the sum of the first n natural numbers using a WHILE loop
DECLARE
n NUMBER; -- Variable to hold the user input
a NUMBER := 1; -- Counter for the WHILE loop
sum_of_n number:= 0; -- Variable to hold the sum of numbers

BEGIN -- Prompt the user to enter a value for n


DBMS_OUTPUT.PUT_LINE('Enter the value of n:');
n := :n; -- Accept input from the user
-- Calculate the sum using a WHILE loop
WHILE a <= n LOOP
Sum_of_n := sum_of_n + a;
a := a + 1;
END LOOP; -- Display the result
DBMS_OUTPUT.PUT_LINE('The sum of the first ' || n || ' natural numbers is: ' || sum_of_n);
END; /

15 Prepared By:-
Darshana V.Halatwala
For Loop
This loop is used when some statements in PL/SQL code blocks are to be repeated
for a fixed number of times.

When we use the for loop we are supposed to define a counter variable which
decides how many times the loop will be executed based on a starting and ending
value provided at the beginning of the loop.

The for loop automatically increments the value of the counter variable by 1 at the
end of each loop cycle.

The programmer need not have to write any instruction for incrementing or
decrementing value.

Syntax:
FOR counter_variable IN

start_value..end_value LOOP

statement to be executed

END LOOP;

Time for an Example!

In the example below we have used a for loop to print numbers from 1 to 10.

16 Prepared By:-
Darshana V.Halatwala
DECLARE
i number(2);

BEGIN

FOR i IN 1..10 LOOP


dbms_output.put_line(i);
END LOOP;
END;

FOR loop to calculate the factorial of n pl/sql block


DECLARE
n NUMBER; -- Variable to hold the user input
factorial NUMBER := 1; -- Variable to store the factorial result
BEGIN -- Prompt the user to enter a value for n
DBMS_OUTPUT.PUT_LINE('Enter the value of n:');
n := :n; -- Accept input from the user
-- Calculate the factorial using a FOR loop
FOR i IN 1 .. n
LOOP
factorial := factorial * i;
END LOOP;
-- Display the result
DBMS_OUTPUT.PUT_LINE(n || '! (Factorial of ' || n || ') is: ' || factorial);
END; /

Example:-
Write a PL/SQL block to display the employee whose ID is 110.
Note: Create the table
Table: employees
employee_id integer
first_name varchar(25)
last_name varchar(25)
email varchar(25)
phone_number varchar(15)
hire_date date
job_id varchar(25)
salary integer

17 Prepared By:-
Darshana V.Halatwala
pl/sql Block:-
DECLARE
v_first_name employees.first_name%TYPE;
v_last_name employees.last_name%TYPE;
v_email employees.email%TYPE;
v_phone_number employees.phone_number%TYPE;
v_hire_date employees.hire_date%TYPE;
v_job_id employees.job_id%TYPE;
v_salary employees.salary%TYPE;
BEGIN
SELECT first_name, last_name, email, phone_number, hire_date, job_id, salary
INTO v_first_name, v_last_name, v_email, v_phone_number, v_hire_date,
v_job_id, v_salary FROM employees WHERE employee_id = 110;

DBMS_OUTPUT.PUT_LINE('Employee Details:');
DBMS_OUTPUT.PUT_LINE('Name: ' || v_first_name || ' ' || v_last_name);
DBMS_OUTPUT.PUT_LINE('Email: ' || v_email);
DBMS_OUTPUT.PUT_LINE('Phone: ' || v_phone_number);
DBMS_OUTPUT.PUT_LINE('Hire Date: ' || TO_CHAR(v_hire_date, 'YYYY-
MM-DD'));
DBMS_OUTPUT.PUT_LINE('Job ID: ' || v_job_id);
DBMS_OUTPUT.PUT_LINE('Salary: ' || v_salary);

END; /

➢ User-Defined RECORD and TABLE data types:

1) %TYPE

It stores the value of that variable whose data type is unknown and when we
want the variable to inherit the datatype of the table column.

Also, its value is generally being retrieved from an existing table in the
database, hence it takes the datatype of the column for which it is used.
18 Prepared By:-
Darshana V.Halatwala
Syntax:-
<var_name> <tab_name>.<column_name>%TYPE;

Example:
SALARY EMP.SAL % TYPE;
1. Student sno %TYPE;, where Student is the name of the table created in the
database and sno is variable whose data type is unknown and %TYPE is used to
store its value.

Example
CREATE TABLE employees ( emp_id NUMBER(10), emp_name VARCHAR2(50), salary
NUMBER(10, 2) );
DECLARE
v_emp_id employees.emp_id%TYPE; -- Matches the data type of emp_id
v_emp_name employees.emp_name%TYPE; -- Matches the data type of emp_name
v_salary employees.salary%TYPE; -- Matches the data type of salary BEGIN -- Assigning
values
v_emp_id := 101;
v_emp_name := 'JohnDoe';
v_salary := 55000.50; -- Output the values
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || v_emp_id);
DBMS_OUTPUT.PUT_LINE('Employee Name: ' || v_emp_name);
DBMS_OUTPUT.PUT_LINE('Salary: ' || v_salary);
END;

2) %ROWTYPE:-

The %ROWTYPE attribute is used to declare a record type that represents a row in a
table. The record can store an entire row or some specific data selected from the table. A
column in a row and corresponding fields in a record have the same name and data types.

syntax :
<var_name> <tab_name>%ROWTYPE;

Where <variable_name> is the variable defined in the <tab_name>.


Consider a declaration.
EMPLOYEE EMP % ROW TYPE;

This declaration will declare a record named EMPLOYEE having fields with the same name and
data types as that of columns in the EMP table. You can access the elements of EMPLOYEE
record as
EMPLOYEE.SAL := 10000;
EMPLOYEE.ENAME := ‘KIRAN’;

19 Prepared By:-
Darshana V.Halatwala
Example:
DECLARE
E EMP1%ROWTYPE;
BEGIN
E.EMP_No := 2092;
E.ENAME := 'Sanju';
E.ph_no :=5678;
Insert into emp1(EMP_NO, ENAME,ph_no)
values(E.emp_no, E.ename,E.ph_no);
dbms_output.put_line('Row Inserted');
END;

3.3. Exceptions
3.3.1. User defined Exceptions and Pre-defined Exceptions
3.3.2. Handling Exceptions
3.3.3. Raising Exceptions
3.4. Working with Views

Exception Handling in PL/SQL:-


Exceptions are runtime errors or unexpected events that occur during the execution
of a PL/SQL code block.
The oracle engine is the first one to identify such an exception and it immediately
tries to resolve it by default exception handler.
The default exception handler is a block of code predefined in the memory to take
the appropriate action against exceptions.
Exception handling can be done in the EXCEPTION part of PL/SQL program
code block.

20 Prepared By:-
Darshana V.Halatwala
Syntax:-
DECLARE
-- Declaration statements;
BEGIN
-- SQL statements;
-- Procedural statements;
EXCEPTION
-- Exception handling statements;
END;
There are two types of exceptions:
1. System (pre-defined) Exceptions
2. User-defined Exceptions
1. User-defined Exceptions[Custom exception]
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.
3 steps
1. Create an error
2. Raise an error
3. Handle an error
The syntax for declaring an exception is
− DECLARE
my-exception EXCEPTION;
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.

21 Prepared By:-
Darshana V.Halatwala
Syntax:-
DECLARE
<exception name> EXCEPTION
BEGIN
<sql sentence>
If <test_condition> THEN
RAISE <exception_name>;
END IF;
EXCEPTION
WHEN <exception_name> THEN
-- some action
END;

Example:-

DECLARE
sno stu1.rollno%type;
snm stu1.sname%type;
crno stu1.total_course%type;
invalid_total EXCEPTION;
BEGIN
sno := :rollno;
snm := :sname;
crno:=:total_courses;
IF (crno > 3) THEN
RAISE invalid_total;
END IF;
INSERT into stu1 values(sno, snm, crno);
EXCEPTION
WHEN invalid_total THEN
dbms_output.put_line('Total number of courses cannot be more than 3');
END;
Example 2:-

DECLARE
i number;
invalid_num EXCEPTION;
BEGIN
FOR i IN 1..10 LOOP
IF i=7 THEN
RAISE invalid_num;
ELSE dbms_output.put_line(i);
END IF;
END LOOP;

22 Prepared By:-
Darshana V.Halatwala
EXCEPTION WHEN invalid_num THEN
dbms_output.put_line('ERROR 7!');
WHEN others THEN
dbms_output.put_line('ERROR!');
END;
/

2.System (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.

Syntax:-

EXCEPTION

WHEN <exception_name> THEN

-- take action

Named Exception Meaning


Occurs when invalid username or invalid password is given while connecting to
LOGIN_DENIED
Oracle.
TOO_MANY_ROWS Occurs when select statement returns more than one row.
VALUE_ERROR Occurs when invalid datatype or size is given by the user.
NO_DATA_FOUND Occurs when no records are found.
Occurs when a unique constraint is applied on some column and execution of
DUP_VAL_ON_INDEX
Insert or Update leads to creation of duplicate records for that column.
PROGRAM_ERROR Occurs when internal error arise in program.
ZERO_DIVIDE Occurs when the division of any variable value is done by zero.

Example!

23 Prepared By:-
Darshana V.Halatwala
DECLARE

a int;
b int;
c int;
BEGIN
a := :a;
b := :b;
c := a/b;
dbms_output.put_line('RESULT=' || c);
EXCEPTION
when ZERO_DIVIDE then
dbms_output.put_line('Division by 0 is not possible');
END;

Example 2:-
DECLARE
v_emp_name VARCHAR2(50);

BEGIN
-- Attempt to select employee name for a non-existent employee ID

SELECT first_name INTO v_emp_name FROM employees WHERE employee_id = -1;

-- Output the employee name

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

EXCEPTION WHEN NO_DATA_FOUND THEN


-- Handle the exception when no rows are returned

DBMS_OUTPUT.PUT_LINE('Error: No employee found with the given ID.');

END; /
String Example:-
Write a pl/sql block to Count the Number of Vowels in a String
DECLARE
input_string VARCHAR2(100); -- User input
vowel_count int:= 0; -- To store the count of vowels
i int; -- Loop variable
c CHAR(1); -- To store each character in the loop
BEGIN
-- Prompt the user for input
input_string :=:Enter_String; -- Accept user input

24 Prepared By:-
Darshana V.Halatwala
-- Iterate through each character in the string
FOR i IN 1..LENGTH(input_string) LOOP
c := LOWER(SUBSTR(input_string, i, 1));
-- Check if the character is a vowel
IF c IN ('a', 'e', 'i', 'o', 'u') THEN
vowel_count := vowel_count + 1;
END IF;
END LOOP;

-- Display the count of vowels


DBMS_OUTPUT.PUT_LINE('The string "' || input_string || '" contains ' ||
vowel_count || ' vowel(s).');
END;
/
Write a PL/SQL program to reverse a given number using a WHILE
loop
DECLARE
num NUMBER ; -- User input
rev NUMBER := 0;
rem NUMBER;
BEGIN
num:=:num;
WHILE num > 0 LOOP
rem := MOD(num, 10);
rev := rev * 10 + rem;
num := TRUNC(num / 10);
END LOOP;
DBMS_OUTPUT.PUT_LINE('Reversed Number: ' || rev);
END;
/

Write a PL/SQL program to calculate the sum of the digits of a given


number using a WHILE loop.
DECLARE
num NUMBER; -- User input
sum_digits NUMBER := 0;
rem NUMBER;
BEGIN
num:=:num;

25 Prepared By:-
Darshana V.Halatwala
WHILE num > 0 LOOP
rem := MOD(num, 10);
sum_digits := sum_digits + rem;
num := TRUNC(num / 10);
END LOOP;
DBMS_OUTPUT.PUT_LINE('Sum of Digits: ' || sum_digits);
END;
/
ODD/EVEN

If mod(n,2)=0

26 Prepared By:-
Darshana V.Halatwala

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy