Unit-3-PL-SQL
Unit-3-PL-SQL
1) Declaration section
❖ This section declares variables, constants, cursors, and user-defined types.
❖ It begins with the keyword DECLARE.
2) Executable section
1 Prepared By:-
Darshana V.Halatwala
3) Exception-handling section
2 Prepared By:-
Darshana V.Halatwala
v_ph_no :=:ph_no;
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
3 Prepared By:-
Darshana V.Halatwala
● Difficult to separate HTML development with PL/SQL development
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 Prepared By:-
Darshana V.Halatwala
specific function) in
a PL/SQL block.
This datatype is used to store numeric data. Here, p is precision and s is scale.
Example:
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:
3) VARCHAR(size)
· Occupies the whole declared size of memory even if the space is not utilized
by the data.
Example:
4) VARCHAR2(size)
6 Prepared By:-
Darshana V.Halatwala
· It releases the unused space in memory, hence saving the unused space.
Example:
5) DATE
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
DECLARE
v_emp_id := 101;
v_emp_name := 'JohnDoe';
END;
7) BOOLEAN
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.
Example:-
sales number(10, 2);
name varchar2(25);
For example −
counter binary_integer := 0;
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;
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.
1) Basic 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
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;
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
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; /
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;
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
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;
/
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
-- take action
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
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;
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