Cs405 Handouts by Kha
Cs405 Handouts by Kha
Page | 1
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Contents
Module-01: Conceptual Data Modeling & Entity Relationship Diagram (ERD) Review ................. 3
Module 02: Introduction to Oracle 11g on Cloud. ................................................................................. 9
Module 03: SQL Recap .................................................................................................. 12
Module 04: PL/SQL Concepts ....................................................................................... 21
Module 05: General Programming Language Fundamentals of PL/SQL ..............................................24
Module 06: SQL in PL/SQL............................................................................................. 27
Module 07: Conditional Control – I ............................................................................... 36
Module 08: Conditional Control – II .............................................................................. 44
Module 09: Iterative Control – I ..................................................................................... 50
Module 10: Iterative Control – II .................................................................................... 63
Module 11: Cursor ........................................................................................................ 68
Module 12: Error Handling & Built-in Exceptions ................................................................................79
Module 13: User Defined Exceptions ............................................................................ 85
Module 14: Advance Exceptions ................................................................................... 88
Module 16: Collection ................................................................................................... 92
Module 17: Records ...................................................................................................... 98
Module 18: Procedures. .............................................................................................. 102
Module 19: Functions ................................................................................................. 111
Module 20: Triggers ..................................................................................................... 117
Module 20: Package .................................................................................................... 122
Page | 2
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
1. Concept of ERD
Entity–relationship modeling was developed by Peter Chen and published in 1976; it serves as
building block of relational database design. Entity relationship diagram is a graphical
representation of the relationships between data in a database. It is the result of using
systematic process and it just only visualize the business data instead of defining the business
process. In very simple terms, ERD is a visual representation of data that describes how the
data is related to each other.
2. Components of ERD
There are three main components of ERD and these are:
Entity
Attributes
Relationships
3. Entity & Attributes
The word entity is rooted from the Latin word “en” which means being. Entity is name of place,
person or thing about which something can be stored in a system. An entity can be a real-world
object that can be easily identifiable. For example, in a school database, students, teachers,
classes, and courses offered can be considered as entities. All these entities have some
attributes or properties that give them their identity. An entity set is a collection of similar types
of entities.
Entities are represented by means of their properties, called Attribute or Column. All attributes
have values which are the qualities or data about Entities that is to be stored. An Attribute
describes a property or characteristics of an entity. Continuing with the above example, a
student entity may have name, class, and age as attributes. Attribute is the smallest storage
unit of any database.
4. Relationships
Relationship represents how data is connected among entities in a given System. The
association among the entities can also be termed as relationships. In our school example, the
two entities e.g. student and course have an association or relation with each other as student
enroll in a course. Interaction among entities is captured using relationships. In a database,
relationships are created between different entities in order to remove the redundancy and
ultimately improve the database performance.
Relationship define how data is connected among the entities in a given system or in other
words how one entity is logically connected with another entity of the system. Relationships in
Page | 3
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Page | 4
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
6. Cardinality
Cardinality expresses the maximum number of record which is present in child table per parent
record in parent table. It can either be 1 or more than one represented by > or < symbol.
Cardinality is read with opposite entity.
7. One-To-Many Relationship
A one-to-Many relationship is a type of cardinality that refers to the relationship between two
entities A and B in which one record of entity A may be linked to zero, 1 or more records in
entity B. Primary key of parent table will be written as Foreign Key in child table as a rule.
Consider the following illustrations:
Illustration 01:
Page | 5
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
8. Many-To-Many Relationship
A many-to-many relationship is a type of cardinality that refers to the relationship between two
entitiesA and B in which A may contain a parent record for which there are many children in B
and vice versa. This means that a parent row in one table contains several child rows in the
second table, and vice versa. Many-to-Many relations are tricky to represent and are not
supported directly in the relational environment from implementation view point. To represent
this kind of relationships, a third entity or intersection table is created where primary key (PK)
of two tables act as foreign key (FK) and composite primary key (CPK) in third table. Many-to-
many relationships are resolved into two one-to-many relationships, as shown below.
Relationship from A to A_B: A is having ZERO (dotted line) or More (<)occurrence in A_B
Relationship from B to A_B: B is having exactly ONE (solid line) or more (>)occurrence in
A_B
9. One-To-One Relationship
A one-to-one relationship is a type of cardinality that refers to the relationship between two
entities A and B in which one record of A may only be linked to one or zero record of B.
It is important to note that a one-to-one relationship is not a property of the data, but rather of
the relationship itself as there is no parent-child relationship in on-to-one relation scenario. The
following are rules to implement One-to-One:
i. There will be foreign key in any one of the participating table.
ii. Foreign key will be made as Unique key.
Page | 6
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
In a Building apartment renting scenario, there are apartments, buildings and customers. There
are multiple floors in the building and on each floor there are multiple apartments, floor can
have zero or no apartment. Each apartment can be rented at most one customer but customer
can rent out multiple apartments from same building and apartment can be available on
multiple floors or same. At the end of month a receipt is generated against which a rent is
deposited.
The following entities can be derived from the above stated scenario:
BUILDING
APARTMENT
CUSTOMER
FLOOR
RECEIPT
Page | 7
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
There are musical bands which record songs and request musical companies to launch their
songs in the form of Album. Songs are written by song writers. Album can contain at least one
song to be album and max of 12 songs. Writer can write multiple songs but songs are usually
written irrespective of the number of person in the bands.
Page | 8
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Step 02:
Click on the Sign In button on the upper right corner of the page and enter the following
credentials:
Workspace Name
Username
Password
Page | 9
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Step 03:
Step 04:
Click on SQL Commands tab from the drop down list to access the code or enter SQL
Statements / Commands and click Run to see the results
Page | 10
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Page | 11
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
1. Select Statement
Data Retrieval Language (DRL) is a command to retrieve data from a database object in the
desired format. This is the most popular / flexible and the only way to retrieve data from a
database. Command used for this purpose is called SELECT which allow us to specify the type of
information which we want to retrieve. SELECT statements take the assumption that the tables
are created and data has been populated in them. The basic syntax of SELECT statement is as
follows:
SELECT distinct * | ColumnName FROM TableName;
Where:
* mean all the column
ColumnName is one or more column from table
Distinct mean unique values from column
Details: It will display only deptno (column) and all rows from EMP Table.
Details: It will display only unique deptno (column) and all rows from EMP Table.
Details: It will display complete (all columns and all rows) from EMP Table.
each row of the table. If the given condition is satisfied then only it returns specific value from
the table. You would use WHERE clause to filter the records and fetching only necessary
records. The syntax would be like:
SELECT distinct * | ColumnName FROM TableName WHERE condition 1 and / or condition 2 and
/ or condition 3
Where conditions can include: >, <, =, <>, AND, OR, NOT
Thing to be remember is thatf there
I are multiple conditions in where clause then at a time
only one condition will be evaluated.
Write a query to find out list of all those employee name who are earning more than 2500 but
less than 5000.
Solution:
SELECT ename FROM emp WHERE sal>2500 and sal < 5000;
Example 02:
Write a query to find out all those employees who are working in Dept # 20 with designation of
Analyst but not earning more than 2000 and were hired at least 30 years ago.
Solution:
SELECT * FROM emp WHERE deptno=20 AND Job=‘Analyst’ AND sal <2000 and
hiredate<sysdate -10000;
Note: Only days can be subtracted from Dates, here 10000 days will be subtracted from current
(sysdate) date and then will be compared with hiredate.
Page | 13
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
similar to the MS-DOS wildcard question mark character. The underscore allows for the
substitution of a single character in an expression.
6. Implementing Wildcards – 1 wildcard are implemented using like like operator
Consider the following scenario:
Write a query to display list of name of all those employees who are having either E in the
name or the name should end with G with at least two characters but should be working in
Dept#30 and salary at least 1500.
Details: This query will return all the columns (*) and only those rows which are either have E
due to % sign there can be zero or more character before and after E or the name should have
two character ending with G, underscore (_)G is taking care of atleast two characters ending
with G and department should belong to 30 and salary should be greater than 1500 (at least is
translated into greater than or equals to (>=)
7. Implementing Wildcards – 2
Another scenario is: Write a query to display all information about all those employees who are
having ER in the job with at least three characters in job and should be earning at least 2500 but
less then
at most 5000 and should be with company for at most 15 years
Greater then
SELECT * FROM emp WHERE job like ‘%ER-%’ AND sal > 2500 AND sal < 5000 AND hiredate
<=sysdate – 5600;
SELECT ename, LENGTH (ename), INSTR (ename, 'A'), CONCAT (ename,job) FROM emp WHERE
instr(ename,'A')=3;
SELECT SUBSTR ('ABCDEFG', 3, 4) "Substring" FROM DUAL;
Page | 14
Virtual University of Pakistan
Handouts
9. Group Functions
These functions manipulate groups of rows to give one result per group of rows. Group
functions compute an aggregate value based on a group of rows. Group functions cannot be
used with the WHERE clause. The example of the group or multiple row function is given below:
10. Implementing Group Functions - 1:
Scenario: Write a query to display sum, minimum, maximum and average salaries which
company is paying to its employees
Solution: group function types
SELECT COUNT (*), sum (sal), min (sal), max (sal), Avg (sal) from emp;
Details: SQL Statement will return five columns and one rows
SELECT COUNT (*), sum (sal), min (sal), max (sal), Avg(sal) from emp WHERE deptno !=20 and
avg (sal) <=1500;
Details: Group functions can’t be used in where clause. Only single row functions are allowed in
Where clause. The result of this query would be and Error because, as mentioned above, group
functions cannot be used with the WHERE clause.
Page | 15
Virtual University of Pakistan
Handouts
Need to group together all rows of each department separately i-e creating groups
Need sum of salary each department – group
SELECT SUM (sal), deptno FROM emp
GROUP BY deptno;
Page | 16
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Details: Where and Group by clause can be used together as far as Group functions are not used
where clause.
Solution – 2
Details: Only those columns can come after Select clause which are written after Group By
clause. Result – Error job, mrg are not written after group by clause
15. HAVING Clause to restrict groups (only used groups in having lause)
The having clause, is just like the where clause, that filters the results in aggregated / grouped
data. The Where clause cannot be used in the aggregated data, so SQL having clause is
introduced to filter the results. The HAVING clause enables you to specify conditions that filter
which group results appear in the final results.
The WHERE clause places conditions on the selected columns, whereas the HAVING clause
places conditions on groups created by the GROUP BY clause.
Page | 17
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Solution:
SELECT max (sal) , min(sal) FROM emp
WHERE ename not like ‘%A%’ or comm is null and months_between(sysdate, hiredate)>6
GROUP BY deptno
HAVING max(sal) > 4500 and avg(sal)<1500;
18. ORDER BY Clause can use independent of where or group by or having clause
The Order by clause is used with the SQL SELECT statement to sort the results in ascending or
descending order. You have to specify one or more columns for what you want to sort the table
result set. The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in a descending order, you can use the DESC keyword. The basic syntax is as follows:
SELECT column_name,
FROM table_name
ORDER BY column_name ASC|DESC,
Page | 18
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
22. What are Self Joins? (when PK and FK belong to same table)
A self-join is a query in which a table is joined (compared) to itself. Self-joins are used to
compare values in a column with other values in the same column in the same table. In self-join
a table is joined with itself, especially when the table has a FOREIGN KEY which references its
own PRIMARY KEY. To join a table itself, means that each row of the table is combined with
itself and with every other row of the table. Self joins are used in a recursive relationship. To
explain that further, think of a COURSE table with columns including PREREQUISTE, COURS_NO
and others. There is a recursive relationship between PREREQUSITE and COURSE_NO as
PREREQUSITE is valid only if it is also a valid COURSE_NO.
23. Implementing Self Joins - 1
The basic syntax of self-join is:
SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_field = b.common_field;
Page | 19
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
25. SubQueries it is alternate to joins.(a subquery which returns more than one rows then we use IN operator)
A subquery is a query within a query. Subqueries enable you to write queries that select data
rows for criteria that are actually developed while the query is executing at run time. SQL
subquery is usually added in the WHERE Clause of the SQL statement. Most of the time, a
subquery is used when you know how to search for a value using a SELECT statement, but do
not know the exact value in the database. Subqueries are an alternate way of returning data
from multiple tables, or simply, alternative of joins. The general syntax is as follows:
SELECT *
FROM t1
WHERE column1 = (SELECT column1 FROM t2);
Page | 20
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
The client interface is provided through HTML for the newer HTML-based applications, and via
a Java applet in a Web browser for the traditional Forms-based interface. In Oracle Applications
Release 11i, each user logs in to Oracle Applications Server using UI interface and then control
is passed to Application Tier for verification as per Business Logic. Responsibility of Client layer
is to make sure UI layer is presented to user successfully as per requirement.
2. Application Tier
The application tier has a dual role: hosting the various servers that process the business logic,
and managing communication between the desktop tier and the database [Link] tier is
sometimes referred to as the middle tier.
3. Database Tier
The database tier contains the Oracle database server, which stores all the data maintained by
Oracle Applications. The database also stores the Oracle Applications online help information.
More specifically, the database tier contains the Oracle data server files and Oracle Applications
Page | 21
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
database executable that physically store the tables, indexes, and other database objects for
your system. In general, the database server does not communicate directly with the desktop
clients, but rather with the servers on the application tier, which mediate the communications
between the database server and the clients.
SQL is for iteract with database but pl is for programming language constructs using sql.
2. What is PL/SQL? it is a declarative language. which use already defined commands.
PL/SQL stands for Procedural Language Extension to SQL. PL/SQL extends SQL by adding
programming structures and subroutines available in any high-level language. PL/SQL is a
procedural language designed specifically to embrace SQL statements within its syntax. PL/SQL
program units are compiled by the Oracle Database server and are stored inside the database.
And at run-time, both PL/SQL and SQL run within the same server process, bringing optimal
efficiency. PL/SQL automatically inherits the robustness, security, and portability of the Oracle
[Link]/SQL is used for both server-side and client-side development.
3. Why PL/SQL?
Any application which need to access database need interface to access DB and an application
that uses Oracle Database is worthless unless only correct and complete data is persisted. The
longstanding way to ensure this is to expose the database only via an interface that hides the
implementation details -- the tables and the SQL statements that operate on these. This
approach is generally called the thick database paradigm, because PL/SQL subprograms inside
the database issue the SQL statements from code that implements the surrounding business
logic; and because the data can be changed and viewed only through a PL/SQL interface.
Since SQL is a declarative language it lacks language constructs like loops, procedures,
functions; and these construct are required to write generic code, to provide programming
language functionalities to SQL, PL/SQL is used with SQL as an embedded part in it.
4. How PL/SQL Works?
The basic unit of a PL/SQL source program is the block, which groups related declarations and
statements. Block is minimum executable unit of PL/SQL which consists of Mandatory and
Optional Parts. A PL/SQL block is defined by the keywords DECLARE, BEGIN, EXCEPTION, and
END. These keywords partition the block into a declarative part, an executable part, and an
exception-handling part. Blocks can be nested: Because a block is an executable statement, it
can appear in another block wherever an executable statement is allowed. Following is the
basic structure of a PL/SQL block.
Page | 22
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
5. PL/SQL Executable
This section is enclosed between the keywords BEGIN and END and it is a mandatory section. It
consists of the executable PL/SQL statements of the program. It should have at least one
executable line of code, which may be just a NULL command to indicate that nothing should be
executed. Example is as follows:
BEGIN
DBMS_OUTPUT.PUT_LINE (‘First Program in Oracle 11i’);
END;
Detail: The Program will display First Program in Oracle 11i on the screen.
DBMS_OUTPUT.PUT_LINE is equivalent to cout or printf in C++/C
Page | 23
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
DECLARE
I number (10):=0;
Name varchar2(10);
DOB date:=sysdate;
Cost real:=390;
PI CONSTANT NUMBER := 3.141592654;
BEGIN
Dbms_output.put_line (I || name || dob || PI);
END;
In declaration section 5 variables are declared with respective data types. I, Name, DOB,
Cost and PI are variables with associated Data types number (10), varchar2 (10), date,
real and constant number respectively. In PL/SQL variables can only be declared in
declaration section.
To display output on screen Dbms_output.put_line (I || name || dob || PI); is used and
concetnation operator (||) is used to join output of multiple variables on the screen
In declaration section 4 variables are declared with respective data types. a,b,c,f are
variables with associated Data types. In begin section variable C is assigned with new
value which is sum of a and b. Value of c is displayed on screen using
dbms_output.put_line('Value of c: ' || c); . In variable f new value is assigned by dividing 70.0 /
3.0 and value of F is displayed using
Page | 24
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Value of c: 30
Value of f: 23.33333333333333333333333333333333333333
END;
END;
In PL/SQL there can be block within blocks, variables declared in outer block are
accessible in inner block but variables declared inside inner block are not accessible in
outer block. Like variable num1 and num2 are accessible in inner block but variable
num3 is not accessible in outer block. If variable with same is declared in inner and
outer block then value of variable declared in inner block will override the value in inner
block. Output of the program is as follow, value of num2 which is declared in both outer
and inner block, value of 195 (declared in inner block) is shown instead of 85 as
initialized in outer block; however value of num1 is same in inner and outer block as
num1 is declared only in outer block.
Page | 25
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Page | 26
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
By default, a SELECT INTO statement must return only one row. Otherwise, PL/SQL raises the
predefined exception TOO_MANY_ROWS and the values of the variables in the INTO clause are
undefined. The WHERE should contain condition to return at max match one row. Number of
column before and after INTO clause needs to be same with respective data type in order to
run the query.
2. Implementing SELECT INTO Syntax – I
DECLARE
Id number (10):=0;
Current_date date;
BEGIN
SELECT 4982, sysdate INTO id, current_date
FROM dual;
dbms_output.put_line('Values are : ' || id || current_date);
END;
/
Explanation:
4982 and sysdate (06/10/2016) are loaded into local variables (id,current_date) and are
Page | 27
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
END;
/
Explanation:
Because there no where clause in SQL statement due to which there are multiple rows return
from the query and Select statement is not able to handle multiple rows.
END;
/
Explanation:
Empno, ename , hiredate are loaded into local variables i-e id,name,hire_date ; since now
there check in where clause on empno which is primary key so it will ensure that at max one
row exists against empno=7369
Output of the Program
Values are: 736912/17/1980KAMRAN
Write a PL/SQL block to retrieve maximum salary of the employee who is not working in
department no 10 but have been associated with organization for past 5 years.
Page | 28
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Solution:
DECLARE
sal number(10):=0;
BEGIN
SELECT max(sal) INTO sal FROM emp
WHERE deptno!=10 and months_between (sysdate,hiredate)>=60;
dbms_output.put_line('Maximum Salary is : ' || sal);
END;
/
Explanation:
Maximum salary is retrieved into local PL/SQL variable i-e sal with employee should not be
working in deptno 10 and due to months_between (sysdate, hiredate) it will return number
of months between current date and hiredate and if number of months are greater than or
equal to 60 i-e 5 years; only then that particular employee will be considered
Value (54072) may vary from student to student as this value is shown in my login on
[Link]
To do Questions by Students:
Write a PL/SQL block to retrieve maximum, minimum number of the employee who is not
working as Analyst but belong to department having at least employees.
6. DML in PL/SQL
Getting data into and out of a database are two of the most important features of a database. It
is possible to use DML statements INSERT, UPDATE and DELETE in PL/SQL while having no
limitation on number of rows to be affected. Just to recap, brief explanation o DML statements
is provided below:
INSERT: The INSERT statement inserts rows into an existing table.
UPDATE: The UPDATE statement updates (changes the values of one or more column)
from a set of existing table rows.
DELETE: The DELETE statement deletes rows from a table.
Page | 29
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
There is no change in syntax while using DML in PL/SQL, same syntax is true when
DML is used outside PL/SQL
Write a PL/SQL block the set the salary of employee no 7369 increment by 25% of the
maximum salary earned by any employee
Solution:
DECLARE
No number(10):=2;
salary [Link]%type;
BEGIN
SELECT max (sal) INTO salary FROM emp;
UPDATE emp set sal = sal +salary*0.25 WHERE empno=7369;
dbms_output.put_line('Row Updated');
SELECT sal INTO salary FROM emp WHERE empno=7369;
dbms_output.put_line('Updated Salary' || salary);
END;
Explanation:
In first SQL query, maximum salary is loaded into local variable salary
In update command salary of empno: 7369 is added with 25% of maximum salary (salary
variable)
In last SQL query: Updated Salary is loaded into salary (local variable) and then displayed it on
the screen
Page | 30
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Row Updated
Updated Salary84487
Write a PL/SQL block to insert a new row in employee table (empno, ename) only and code
should not violate primary key constraint assuming empno is PK and for ename any ‘ALLEN’ can
be used.
Solution:
DECLARE
max_no [Link]%type;
BEGIN
SELECT MAX (empno) INTO max_no FROM emp;
INSERT INTO emp (empno, ename) values (max_no+1, 'ALLEN');
dbms_output.put_line ('Row added');
END;
Explanation:
In first SQL Query maximum empno is loaded into local variable max_no
In limited column Insert statement empno is max_no+1 (this will always ensure PK is unique)
and ename is ALLEN.
Output of the Program:
Row Added
Note: There can be more than one solution to a same problem
Write a PL/SQL block to increase salary by 15% as retention bonus of all those employees who
have been associated with company for more than 10 years
Page | 31
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Solution:
BEGIN
UPDATE emp set sal = sal*0.15 + sal
WHERE months_between (sysdate, hiredate)>120;
dbms_output.put_line('Salary updated');
END;
Write a PL/SQL block which should insert primary key in the table using sequence in consistent
way without unique key violation. Assuming there is existing data in primary key column.
Solution
CREATE table product (id number (10) primary key, pname varchar2(30));
INSERT INTO product values(1, 'HD');
select emp_no.nextval, emp_no.currval from dual;
Page | 32
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
DECLARE
pid number (10):=0;
new_id number(10):=0;
BEGIN
SELECT max (id) into pid from product;
dbms_output.put_line ('Maximum id : ' || pid);
dbms_output.put_line ('Next Value of PK ' || ( pid + emp_no.nextval ));
insert into product values (pid + emp_no.nextval, 'HD');
dbms_output.put_line( ' Row Successfully added');
END;
Explanation:
In PL/SQL Code:
Page | 33
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Page | 34
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
SAVEPOINT B;
ROLLBACK to A;
SELECT COUNT (*) into total_rows FROM product;
dbms_output.put_line( ' Total rows inserted : ' || total_rows);
END;
Explanation:
Note: Should be inserting 2 but due to SAVEPOINT one row is rollback
Page | 35
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
1. IF – THEN Statements
This statement is used to execute the statement if the condition provided is true. The IF
statement associates a condition with a sequence of statements enclosed by the keywords
THEN and END IF. If the condition is TRUE, the statements get executed, and if the condition is
FALSE or NULL, then the IF statement does nothing. END IF is to be used for each IF condition
as shown in the following syntax:
BEGIN
IF condition THEN
Statement -1;
Statement -2;
END IF;
END;
Write a PL/SQL block to insert a row in emp table if total number of employees in department #
20 are more less than 50 because as policy maximum number of employees can be 50 in any
department
Solution is not possible with SQL only because now conditional insertion of data in table is
required. This create the need for control structure
Solution:
DECLARE
total number (10):=0;
max_id number(10):=0;
BEGIN
SELECT count (*) into total FROM emp WHERE deptno=20;
SELECT max (empno) into max_id from emp;
END IF;
END;
Write a PL/SQL block to update the salary of all the employees if there are at least 15
employees in the company and out of at least 5 have been attached with organization for more
than 5 years then raise the salary of all the employee by 10%.
Solution
DECLARE
total_emp number(10):=0;
total number(10):=0;
percentage real(10):=0.10;
BEGIN
SELECT COUNT (months_between (sysdate, hiredate)) into total_emp from emp WHERE
months_between (sysdate, hiredate)>=60;
SELECT COUNT (*) into total FROM emp;
END IF;
END;
Explanation:
First SQL is counting total employees who are attached with organization for more than 5
years and Second SQL is counting total employees in the organization.
Conditional Increment is given using IF clause if total employees are greater than 15 and those
who are attached with organization is more than 5.
Output:
Increment given
Page | 37
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
BEGIN
IF condition THEN
Statement -1;
Statement -2;
ELSE
Statement-1;
END IF;
END;
Write a PL/SQL block to check whether you are logged in as ‘APEX_PUBLIC_USER’ and if this is
true then display success message and then check whether maximum salary has been achieved
against designation of ANALYST or not. As company policy maximum salary which can be paid
to Analyst is not more than 5000 otherwise display message not achieved.
Solution
DECLARE
max_sal number(10):=0;
designation varchar2(30):='ANALYST';
BEGIN
SELECT MAX (sal) INTO max_sal FROM emp WHERE job=designation;
IF user = 'APEX_PUBLIC_USER' and max_sal <=5000 THEN
dbms_output.put_line ('Current Maximum Salary for ' || designation || ' is : ' || max_sal);
dbms_output.put_line ('Maximum Salary not achieved');
ELSE
dbms_output.put_line ('Maximum achieved');
END IF;
END;
Explanation:
User is the environment variable which is holding value which is recognizable by system as
Schema user i-e APEX_PUBLIC_USER i-e This is default user value
Maximum Achieved
Page | 38
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
I. Salary > 3000 and less than 6000 and designation = ‘MANAGER’
Message: Senior Management
II. Not part of Management
Solution
DECLARE
designation [Link]%type;
salary [Link]%type;
BEGIN
select job , sal into designation, salary from emp where empno=7369;
IF designation =‘ANALYST' and salary > 3000 and salary < 6000 THEN
dbms_output.put_line(‘Senior Management');
ELSE
dbms_output.put_line(‘Not Part of Management');
END IF;
END;
7. ELSIF Statement
The IF THEN ELSIF statement runs the first statements for which condition is true. Remaining
conditions are not evaluated. If no condition is true, the else statements run, if they exist;
otherwise, the IF THEN ELSIF statement does nothing. There will be one END IF per IF keyword.
The basic syntax is as follows:
BEGIN
IF condition THEN
Statement -1;
Statement -2;
Page | 39
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
END;
ELSIF designation='MANAGER' and salary > 3000 and salary < 6000 THEN
dbms_output.put_line('Senior Management');
ELSE
dbms_output.put_line('Not part of Management');
ENF IF;
END;
Note: The output of the program may vary depending on data available in emp table of
student account
Page | 40
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
END IF;
DBMS_OUTPUT.PUT_LINE('Done...');
END;
Explanation:
V_date is initialized with 18-Dec-2013, to_char (v_date, ‘DAY’) will return DAY on 18-Dec-2013.
There are multiple IF and ELSIF structure as per requirement, point to note is that there is only
one END because there is only ONE if keyword
Done...
Page | 41
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
END IF;
END IF;
dbms_output.put_line('Exact value of a is : ' || a );
dbms_output.put_line('Exact value of b is : ' || b );
END;
Explanation:
First IF condition will be evaluated to TRUE if value of a is between 0 and 100 (0 and 100 are
included) only then next IF will be checked for TRUE or FALSE, in next IF condition will be
evaluated to TRUE is value of b is between 101 and 200, if both IF conditions will be true only
then dbms_output.put_line('Value of a is 100 and b is 200' ); will get executed. In this case
both IF conditions are true (as shown in output below)
Output of the Program
Page | 42
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
END IF;
dbms_output.put_line('Exact value of a is : ' || a );
dbms_output.put_line('Exact value of b is : ' || b );
END;
ii. Write a PL/SQL block to check whether number of employess in Emp table are odd
or even, if number of employees are odd then display message ‘ Odd number of
employees else display ‘ Even number of employees’
1. Case Statement
Case statements are alternate to the IF-Then statements. The CASE statement chooses from a
sequence of conditions, and executes a corresponding statement. This statement selects ONLY
one sequence of statement to execute and when IF case is not matched then else part is
executed. Exception is raised when ELSE part is not written with no matching case in IF
Page | 43
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
condition. But still this statement is considered to be more readable and efficient. The syntax is
given below:
CASE selector
END CASE;
END;
Explanation:
Value of local variable grade is initialized with A, in the case statement first case is matched
and respective message (Excellent) is displayed. Whenever case is matched related
statements are executed and control is transferred after END CASE.
Output of the Program
Excellent
Page | 44
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Solution:
BEGIN
CASE user
WHEN 'APEX_PUBLIC_USER' then dbms_output.put_line(user || ' is Test User');
WHEN 'SCOTT' then dbms_output.put_line(user|| 'Owner of Schema');
WHEN 'DBA' then dbms_output.put_line(user || 'Admin User');
ELSE dbms_output.put_line('Not a Valid user');
END CASE;
END;
Output of the Program:
APEX_PUBLIC_USER is Test User
Page | 45
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
If no case condition is evaluated to be true and there is no else then exception is raised
Solution:
Page | 46
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
END CASE;
END;
Explanation:
As per requirement, maximum sal is loaded into local variable salary and then conditions are
written after WHEN clause as per question. Point to note here is that variable name after CASE
key word rather there is WHEN keyword with condition. In every WHEN clause insert
statement is executed depending on the case. As per data in the tables, following output is
generated and row is inserted in salary_stats table. ELSE part is executed here because no
CASE was matched, if there would have been no ELSE part then program will throw exception
Note: The output of the program may vary depending on data available in emp table of
student account
Solution
DECLARE
jobid [Link]%TYPE;
empid [Link]%TYPE := 7369;
sal_raise NUMBER(3,2);
BEGIN
SELECT job INTO jobid from emp WHERE empno = empid;
CASE
WHEN jobid = 'CLERK' THEN sal_raise := .09;
update emp set sal = sal + sal*sal_raise where empno=empid;
dbms_output.put_line ('Salary raised by ' || sal_raise);
Page | 47
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
END CASE;
END;
Explanation:
As per data in emp table there is not matching JOBID i-e CLER OR MANAGER OR ANALYST,
control is transferred to ELSE part of the program, in the else part there is no
dbms_output.put_line statement so effectively there will no output on the screen. As shown
below: Statement Processed is showing that there is not syntax error and code is executed
successfully only.
Statement Processed
Note: The output of the program may vary depending on data available in emp table of
student account
Practice Question:
Page | 48
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Page | 49
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
1. Simple Loop
The simple loop is different from other loops available in other programming languages; simple
loop consists of a structure to repeat statements. The sequence of statements is executed in
each iteration and it needs a termination in terms of exit statement to stop the loop. Loop
without exit condition considers to be an infinite loop. Sequence of statement(s) may be a
single statement or a block of statements. Loop will keep on execution the statement as long as
exit condition is FALSE and will terminate as soon as exit condition is evaluated to true, this
behavior is totally opposite other type of loops (FOR, WHILE, DO-WHILE). The basic condition is
given in the followings:
LOOP
Statement -1;
Statement -2;
End loop;
End;
BEGIN
LOOP
dbms_output.put_line (rep);
END LOOP;
END;
Explanation:
There is no exit condition written in the program to terminate the loop, program will run
indefinitely and will result in abnormal termination. There is no syntax error in the code.
ORA-10260: limit size () of the PGA heap set by event 10261 exceeded ORA-10260: limit size
(1024000) of the PGA heap set by event 10261 exceeded
Page | 50
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
BEGIN
LOOP
if rep >=5 then
dbms_output.put_line ('Value of Rep: ' || rep);
EXIT;
END IF;
rep:=rep+1;
END LOOP;
END;
Explanation:
Local variable rep is initialized with 0, the loop will keep on executing when rep is <5, as soon
as value of rep is greater than 5 the loop and program will exit.
Output of the Program:
Value of Rep: 5
Write a PL/SQL block to insert 10 row in emp table, add data in empno column only with
starting value of 0 and ending value of 10.
DECLARE
rep number (10):=0;
BEGIN
LOOP
INSERT INTO emp (empno) values (rep);
rep:=rep+1;
EXIT WHEN rep > 10 ;
END LOOP;
END;
Page | 51
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Explanation:
The loop will be in execution when value of rep is less than 11, the loop will run till the
condition of exit (rep>10) is false and will terminate on true condition i-e when value of rep is
greater than 11. In each iteration a row is added in Emp table.
Write a PL/SQL block to display the reverse of maximum salary from EMP table.
DECLARE
N NUMBER(5):=0;
REV NUMBER(5):=0;
R NUMBER(5):=0;
total_emp number(10):=0;
BEGIN
SELECT max(sal) into n FROM emp;
Dbms_output.put_line('maximum Salary is : ' || n);
LOOP
R:=MOD(N,10); --return reminder
REV:=REV*10+R;
N:=TRUNC(N/10);
EXIT WHEN n = 0;
END LOOP;
Dbms_output.put_line(‘Reverse Value : ‘ || rev);
END;
Explanation:
As per output below the maximum salary is 117564 and is loaded into local variable n. and is
displayed.
First iteration:
R = Mod (117564,10) – It will return remainder which is 4
Page | 52
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Rev:=Rev*10 + R = 0*0 + 4 =4
N:=N/10 – 117564 / 10 = 11756 – N is a number due to which float value will not be shown.
Rev:=4*10+6 = 46
N:=N/10 = 11756/10=1175
Third Iteration:
Rev:=46*10+5 = 465
N:=N/10 = 1175/10=117
Fourth Iteration:
Rev:=465*10+7 = 4657
N:=N/10 = 117/10=11
Firth Iteration:
Rev:=4657*10+1 = 46571
N:=N/10 = 11/10=1
Sixth Iteration:
Rev:=46571*10+1 = 465711
N:=N/10 = 1/10=0
Loop will terminate after 6th Iteration.
Output of the Program:
Page | 53
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
6. While Loop
Basic loop structure encloses sequence of statements in between the LOOP and END LOOP
statements. Sequence in statements is executed in each iteration and the loop exits when the
exit condition evaluates to be false. While loop syntax is given below:
WHILE condition LOOP
sequence_of_statements
END LOOP;
END LOOP;
END;
Output of the Program:
This line got printed once only
End loop;
END;
Explanation:
Page | 54
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
3
4
Write a PL/SQL block to insert 10 row in emp table using while loop, populate only empno
column only with starting value of 0 and ending value of 10.
Declare
rep number (10):=0;
Begin
while (rep < 10) loop
insert into emp (empno) values (rep);
rep:=rep+1;
dbms_output.put_line (' Rows are inserted in the loop with row no ' || rep);
END LOOP;
dbms_output.put_line (' Transaction Completed ');
END;
Page | 55
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Write a PL/SQL block to calculate the sum of first 100 even integers starting from 1
DECLARE
counter number(4):=2;
total number(5):=0;
BEGIN
while counter < 100 loop
total:=total+counter;
dbms_output.put_line (' Current Sum is : ' || total );
counter:=counter+2;
END LOOP;
dbms_output.put_line (' Sum of even integers between 1 and 100 is ' || total );
END;
Write a PL/SQL block to calculate the total of first 100 even integers starting from 1, at any
point in time if total exceeds 400 and remain less than 800, add a new row in temp table with
columns of sum, current date and status.
DECLARE
counter number (4):=2;
total number(5):=0;
status varchar2(80):='';
BEGIN
while counter < 100 loop
total:=total+counter;
dbms_output.put_line (' Current Sum is : ' || total );
dbms_output.put_line (' Current Sum is : ' || total );
counter:=counter+2;
if (total > 400 and total < 800) then
Page | 56
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
BEGIN
LOOP
dbms_output.put_line ('Value of count is : ' || current_val);
current_val:=current_val+1;
exit when current_val> 10 ;
END LOOP;
END;
Explanation:
Value of count is : 0
Value of count is : 1
Value of count is : 2
Value of count is : 3
Value of count is : 4
Value of count is : 5
Page | 57
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Value of count is : 6
Value of count is : 7
Value of count is : 8
Value of count is : 9
Value of count is : 10
Statement processed.
END LOOP;
i NUMBER:= 100;
BEGIN
i:=i+1; --Error
END LOOP;
end;
Explanation:
Code is trying to change the value of the For Loop counter (i) in the body of the code, in PL/SQL
For Loop Counter is not allowed to be changed during the body of the code.
Output of the Program:
Page | 58
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
ORA-06550: line 6, column 1: PLS-00363: expression 'I' cannot be used as an assignment target
ORA-06550: line 6, column 1: PL/SQL: Statement ignored 4. FOR i IN 1..10 LOOP 5.
dbms_output.put_line ( ' Value of I : ' ||i); 6. i:=i+1; --Error 7. END LOOP; 8. end ;
END LOOP;
END;
Explanation:
The control will not enter in the loop because to enter in first iteration start_val (10) should be
less than end_val (0) which is FALSE here.
Write a PL/SQL block to insert rows in temp table, if the row inserted is odd then store message
‘Value is odd’ and if the row added is even then display message ‘Value is even’
DECLARE
x NUMBER: = 100;
i number:=0;
BEGIN
FOR i IN 1..10 LOOP
IF MOD (i,2) = 0 THEN -- i is even
dbms_output.put_line('Value of i is even');
INSERT INTO temp VALUES (i, x, 'i is even');
Page | 59
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
ELSE
INSERT INTO temp VALUES (i, x, 'i is odd');
dbms_output.put_line('Value of i is odd');
END IF;
x := x + 100;
END LOOP;
COMMIT;
END;
Value of i is odd
Value of i is even
Value of i is odd
Value of i is even
Value of i is odd
Value of i is even
Value of i is odd
Value of i is even
Value of i is odd
Value of i is even
Page | 60
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
LOOP
DBMS_OUTPUT.PUT_LINE ('Loop counter is ' || i);
END LOOP;
END;
Output of the Program
Loop counter is 5
Loop counter is 4
Loop counter is 3
Loop counter is 2
Loop counter is 1
END LOOP;
END;
Explanation:
Value of loop_start is greater than 1, control will not enter in the loop because loop_start
should be less than 1 to enter in the loop.
Output of the Program
Statement processed.
Write a PL/SQL block to insert rows in temp table, if the row inserted is odd then store message
‘Value is odd’ and if the row added is even then display message ‘Value is even’
DECLARE
x NUMBER := 100;
i number:=0;
Page | 61
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
BEGIN
FOR i IN REVERSE 1..10 LOOP
IF MOD(i,2) = 0 THEN -- i is even
dbms_output.put_line('Value of i is even‘ || i);
INSERT INTO temp VALUES (i, x, 'i is even');
ELSE
INSERT INTO temp VALUES (i, x, 'i is odd‘);
dbms_output.put_line('Value of i is odd');
END IF;
x := x + 100;
END LOOP;
COMMIT;
END;
Note: Make sure temp table empty otherwise there is possibility there Unique
Constraint is violated and exception is thrown.
Value of i is even10
Value of i is odd9
Value of i is even8
Value of i is odd7
Value of i is even6
Value of i is odd5
Value of i is even4
Value of i is odd3
Value of i is even2
Value of i is odd1
Page | 62
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
1. Continue Statement
Continue statement is used to Conditionally Exit from current iteration of loop, the statements
after continue statement are skipped and control is transferred to next iteration. In other
words, it forces the next iteration of the loop to take place, skipping any code in between.
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE ('Inside loop: x = ' || TO_CHAR(x));
x := x + 1;
IF x < 3 THEN
CONTINUE;
END IF;
DBMS_OUTPUT.PUT_LINE ('Inside loop, after CONTINUE: x = ' || TO_CHAR(x));
EXIT WHEN x = 5;
END LOOP;
DBMS_OUTPUT.PUT_LINE (' after loop: x = ' || TO_CHAR(x));
END;
Output of the Program
Inside loop: x = 0
Inside loop: x = 1
Inside loop: x = 2
Inside loop: x = 3
Inside loop: x = 4
Inside loop, after CONTINUE: x = 5
Page | 63
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
After loop: x = 5
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE ('Inside loop: x = ' || TO_CHAR(x));
x := x + 1;
CONTINUE WHEN x < 3;
DBMS_OUTPUT.PUT_LINE
('Inside loop, after CONTINUE: x = ' || TO_CHAR(x));
EXIT WHEN x = 5;
END LOOP;
DBMS_OUTPUT.PUT_LINE (' After loop: x = ' || TO_CHAR(x));
END;
END LOOP;
END;
Page | 64
Virtual University of Pakistan
Join VU Group: [Link]
Handouts (Loop inside loop is called nested loop)
6. Nested Loops
Loop can be nested with any other or same type of loops. A nested loop is a loop within a loop,
an inner loop within the body of an outer one. How this works is that the first pass of the outer
loop triggers the inner loop, which executes to completion. Then the second pass of the outer
loop triggers the inner loop again. This repeats until the outer loop finishes. Of course, a break
within either the inner or outer loop would interrupt this process.
7. Syntax of Nested Loops
LOOP – Main Loop
Sequence of statements1
LOOP – Nested or inner loop
Sequence of statements2
END LOOP;
END LOOP;
END
END LOOP;
END LOOP;
END;
Explanation:
For every iteration of outer loop all the iterations of inner loop will be executed.
Output of the Program
Page | 65
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
END LOOP;
END;
Output of the Program
v_counter1 : 0
Page | 66
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
v_counter2: 0
v_counter1 : 1
v_counter2: 2
v_counter1 : 2
v_counter2: 4
Page | 67
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
3. Types of Cursor
There are following two types of cursor along with their details:
A. Implicit:
This cursor is created automatically by oracle server whenever SQL statements are executed
and the user is unaware of this and cannot control or process the information in an implicit
cursor.
B. Explicit
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. The
advantage of declaring an explicit cursor over an indirect implicit cursor is that the explicit
cursor gives the programmer more programmatic control.
4. Cursor Attributes Cursor:-
Two types and four attributes
There are four attributes of cursors and these are explained in the following table:
No. Attribute Syntax Description
A Boolean attribute that returns TRUE if the
1 %NOTFOUND cursor_name%NOTFOUND previous FETCH did not return a row and FALSE if it
did.
A Boolean attribute that returns TRUE if the
2 %FOUND cursor_name%FOUND previous FETCH returned a row and FALSE if it did
not.
The number of records fetched from a cursor at
3 %ROWCOUNT cursor_name%ROWCOUNT that point in time.
A Boolean attribute that returns TRUE if the cursor
4 %ISOPEN cursor_name%ISOPEN is open and FALSE if it is not.
END IF;
END;
Explanation:
After execution of delete statement, %notfound will return the count of total number
of rows delete, if there are one or more rows got delete then %notfound will be
evaluated to false and control will be passed to ELSIF.
Output of the Program:
Page | 69
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
END IF;
END;
Explanation:
Implicit cursor is attached with every DML statement which get executed and all the
attributes of implicit cursor are attached to lastly executed DML statement. After
execution update statement in the code %rowcount will show total number of rows
effected by update and same is true for delete. The code will insert row in temp table
always because value of total_rows is always 0 in the code.
Output of the Program:
1 Row is Updated
1 Row is inserted
Page | 70
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
END LOOP;
dbms_output.put_line(c1%rowcount || ' Outside loop Row are processed ');
END;
Explanation:
Cursor is defined in Declaration section, Cursor is a name attached with SELECT statement.
When cursor will be open in Begin section it will get two column (ename, job) and all the rows
where deptno=10 and there can be multiple rows. Without Cursor it is not possible that
SELECT statement can return multiple rows but with cursor it is possible. When first row will
be fetched from HardDisk to RAM C1 will be pointing to first row in RAM using fetch keyword.
In the loop value of first row i-e two columns; are loaded into PL/SQL local variable name and
designation. Then name and designation values are displayed on screen. C1%rowcount is
counter which contain value of total number currently fetched. For first iteration
c1%rowcount is 1 as shown in the output below and for next iteration there will be addition of
1 into it. In the exit condition c1%notfound will be evaluated to FALSE because there is next
row in the cursor and control will be transferred back at the start of the loop and C1 will start
pointing to next row in RAM and same process will be repeated. When c1 will be at last row in
the RAM c1%notfound will be evaluated to TRUE because there will be no next row and loop
will terminate.
Output of the Program:
Statement processed.
Note: The output of the program may vary depending on data available in emp table of
student account
Page | 71
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
END LOOP;
END;
Output of the Program
Department no: 30
Job: MANAGER
Department no: 10
Job: MANAGER
Department no: 20
Job: MANAGER
Department no: 30
Job: SALESMAN
Department no: 30
Job: SALESMAN
Department no: 30
Job: SALESMAN
Department no: 30
Job: SALESMAN
Department no: 30
Job: SALESMAN
Note: The output of the program may vary depending on data available in emp table of
student account
Write a PL/SQL to display 4 records from emp table and if these 4 records have maximum salary
among them display maximum salary.
Solution:
DECLARE
cursor c1 is select sal from emp;
max_sal number(10):=0;
sal [Link]%type;
BEGIN
SELECT MAX (sal) into max_sal from emp;
open c1;
LOOP
fetch c1 into sal;
IF sal = max_sal then
dbms_output.put_line ('Maximum salary is reached');
ELSE
dbms_output.put_line ('Maximum salary Not reached');
END IF;
EXIT WHEN c1%rowcount >4;
END LOOP;
Page | 73
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
END;
Output of the Program
Statement processed.
Note: The output of the program may vary depending on data available in emp table of
student account
DECLARE
cursor c1 is select ename, sal from emp order by sal;
name [Link]%type;
salary [Link]%type;
BEGIN
open c1;
LOOP
fetch c1 into name, salary;
dbms_output.put_line('Name : ' || name);
dbms_output.put_line('Salary : ' || salary);
EXIT WHEN c1%rowcount > 4;
END LOOP;
END;
Explanation:
In the cursor Name and Sal are retrieved from emp table but in Ascending order and then in
the loop only first 4 rows are displayed using check on c1%rowcount>4.
Output of the Program
Page | 74
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Name : Special
Salary : 2783
Name : ADAMS
Salary : 8513.197
Name :
Salary : 9680
Name :
Salary : 9680
Name : MILLER
Salary : 9993.4021
Note: The output of the program may vary depending on data available in emp table of
student account
END LOOP;
END;
Output of the Program
Statement processed.
Page | 75
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
END LOOP;
END;
Explanation:
Cursor is open, fetched and closed using FOR Loop. In the FOR loop to process Cursor only
declaration in declare section is required rest of the steps are done automatically by FOR
Loop.
Output of the Program
Statement processed.
Write a PL/SQL block to update the salary of all those employees who are working in
organization for at least 10 years, increase their salary by 20% and display empno, update salary
and currentdate
Solution:
DECLARE
cursor c1 is select empno, sal from emp where months_between(sysdate, hiredate)>120;
eno [Link]%type;
salary [Link]%type;
update_sal number(10):=0;
BEGIN
open c1;
LOOP
fetch c1 into eno, salary;
update_sal:=salary+salary*0.20;
Page | 76
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
END LOOP;
END;
Write a PL/SQL block to insert a row a temp table if sum of salary exceeds 20000 , insert
current sum of salary, total employees having sum of 20000 salary and current date, otherwise
display salary of current employee and name of employee.
Solution:
DECLARE
cursor c1 is select ename, sal from emp;
name [Link]%type;
salary [Link]%type;
total number(10):=0;
rows number(10):=0;
BEGIN
open c1;
LOOP
fetch c1 into name, salary;
total:=total+salary;
rows:=c1%rowcount;
IF (total > 20000) then
INSERT INTO temp values (total, rows, sysdate);
dbms_output.put_line('Total salary : ' || total );
dbms_output.put_line('Total Employees : ' || rows );
dbms_output.put_line('Current Date : ' || sysdate );
END IF;
EXIT WHEN c1%notfound;
END LOOP;
close c1;
END;
Page | 77
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Page | 78
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Internal Exceptions: These are pre-defined and they are executed in case of violations of
any database rule by the program. Internal exceptions are raised automatically.
User-Defined: PL/SQL also allows user to define their own exceptions according to the
need of the program. This type of exceptions is not raised automatically and user should
raise it.
6. Formation of Built-In Exceptions
There are three (03) components of a Built-In Exception:
Exception Name
Exception Unique Number: These are system generated
Page | 79
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Description
Consider the following examples:
7. Syntax of Exception
syntax for short
Below is the basic syntax of an exception:
Declare Section
All the declarations
Begin
Executable statements
End;
Page | 80
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Begin
Executable statements
End;
End;
Explanation:
When Query is executed in begin block and there is no matching record in emp table then
no_data_found exception is raised automatically by the server, in the exception section user
friendly message is displayed by handling the particular exception. If there is any other type of
exception is raised then WHEN others THEN will take care of it. SQLCODE will return code of
the exception raised and SQLERRM will raised the associated message with it.
Output of the Program
Page | 81
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
End;
Explanation:
Exception can be raised with Query and any DML statement like Insert in this code.
Output of the Program
End;
Explanation:
Select is returning more than one row without using cursor, multiple rows return exception will
be raised and control will be transferred to WHEN others THEN.
Page | 82
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
-1422
End;
Explanation:
Local exception (inner block) always overrides exception defined in the outer block. If there is
no matching exception handler in the inner block then program look of exception handler in
outer block.
Output of the Program
KAMRAN
Duplicated values in inner block
Page | 83
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
End;
Exception
when NO_DATA_FOUND then
dbms_output.put_line('No Data found in outer block');
End;
Output of the Program
KAMRAN
No Data found in outer block
Page | 84
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
END IF;
EXCEPTION
WHEN user_define_exception_name THEN
User defined statement (action) will be taken;
END;
Page | 85
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
End;
Output of the Program:
Valid Salary
Write a PL/SQL block to insert row in emp table, while inserting data in emp table if salary is
less than minimum salary then raise an exception other.
Solution:
DECLARE
low_sal EXCEPTION;
min_sal NUMBER:= 10000;
new_sal NUMBER:= 8000;
BEGIN
INSERT INTO EMP(EMPNO, DEPTNO, SAL)
VALUES (4000,20,new_sal);
IF new_sal < min_sal THEN
RAISE low_sal;
END IF;
EXCEPTION
WHEN low_sal THEN
DBMS_OUTPUT.PUT_LINE ('Salary is less than '||min_sal);
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE (SQLERRM);
END;
Output of the Program
past_due EXCEPTION;
acct_num NUMBER;
BEGIN
Page | 86
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
DECLARE
acct_num NUMBER;
BEGIN
RAISE past_due;
END IF;
EXCEPTION
END;
Explanation:
Past_due exception is declared in the outer block but raised in the inner block. Inner block will
first search for past_due exception handler in the inner block first and if there is no exception
handler then exception handler is searched in the outer block
Output of the Program
Page | 87
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
1. Raise_Application_Error
It’s a built-in procedure lets you issue user-defined ORA- error messages from stored
subprograms. That way, you can report errors to your application and avoid returning
unhandled exceptions. It allows system to terminate any PL/SQL block and behave like pre-
define or user define exception.
2. Raise vs Raise_Application_Error must read it and clear your concept
Raise is used to call pre-defined or user-defined exception while on the other hand
Raise_application_erorr let the developer show the customized message with number. PL/SQL
Block terminates the processing when there is some error. If we want to raise an exception and
change the path of processing developer can place RAISE statements. By Raise statement,
developer can raise user defined exceptions.
3. Syntax of Raise_Application_Error
The syntax to Pre-define procedure to return user-friendly message back to user is as follows:
raise_application_error(
error_number, message[, {TRUE | FALSE}]);
Where,
Error_number is a negative integer in the range -20000 to -20999
Message is a character string up to 2048 bytes long
4. Implementing Raise_application_error – I
Declare
name [Link]%type;
salary [Link]%type;
Begin
select ename, sal into name, salary from emp where empno=7369;
if salary <5000 then
Raise_application_error(-20030, ‘Invalid salary’);
else
dbms_output.put_line('Valid Salary');
End if;
Exception
when others then
dbms_output.put_line(SQLERRM);
End;
Page | 88
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Valid Salary
Write a PL/SQL block to retrieve the ename, job, mrg and hiredate for a particular empno and
make sure data is retrieved without error i-e if any field have null value then raise the following
exceptions:
Exception No Message
-20010 No Name
-20020 No Job
-20030 No Manager
-20040 No Hire Date
Declare
v_ename [Link]%TYPE;
v_job [Link]%TYPE;
v_mgr [Link]%TYPE;
v_hiredate [Link]%TYPE;
p_empno [Link]%type:=7654;
BEGIN
SELECT ename, job, mgr, hiredate
INTO v_ename, v_job, v_mgr, v_hiredate FROM emp
WHERE empno = p_empno;
IF v_ename IS NULL THEN
RAISE_APPLICATION_ERROR(-20010, 'No name for ' || p_empno);
END IF;
IF v_job IS NULL THEN
RAISE_APPLICATION_ERROR(-20020, 'No job for' || p_empno);
END IF;
IF v_mgr IS NULL THEN
RAISE_APPLICATION_ERROR(-20030, 'No manager for ' || p_empno);
END IF;
IF v_hiredate IS NULL THEN
RAISE_APPLICATION_ERROR(-20040, 'No hire date for ' || p_empno);
END IF;
DBMS_OUTPUT.PUT_LINE('Employee ' || p_empno || ' validated without errors');
Page | 89
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('SQLCODE: ' || SQLCODE);
DBMS_OUTPUT.PUT_LINE('SQLERRM: ' || SQLERRM);
END;
Output of the Program
Employee 7654 validated without errors
DECLARE
user_define_exception_name EXCEPTION;
PRAGMA EXCEPTION_INIT(user_define_exception_name,-error_number);
BEGIN
statement(s);
IF condition THEN
RAISE user_define_exception_name;
END IF;
EXCEPTION
WHEN user_define_exception_name THEN User defined statement (action) will be taken;
END;
Page | 90
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Begin
SELECT sal in to salary from emp where ename =‘Akbar';
dbms_output.put_line(salary);
Exception
WHEN FOUND_NOTHING THEN
dbms_output.put_line(SQLERRM);
End;
Explanation:
User defined Found nothing exception is associated with built-in exception # 100.
Page | 91
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
A collection is an ordered group of elements, all of the same type. It is a general concept that
encompasses lists, arrays, and other familiar data types. Each element has a unique subscript
that determines its position in the collection anddata is accessed through index which can be
random. Although collection can hold multiple data but still size of collection is dynamic.
2. PL/SQL Tables or Associated Array
Associative arrays are sets of key-value pairs, where each key is unique and is used to locate a
corresponding value in the array. The key can be an integer or a string. Assigning a value using a
key for the first time adds that key to the associative array. Subsequent assignments using the
same key update the same entry. It is important to choose a key that is unique, either by using
the primary key from a SQL table, or by concatenating strings together to form a unique value.
Key thing to remember is that size of the PL/SQL Table is dynamic and index is not needed to be
numeric only i-e Index can be string also, index can be random also meaning user can assign
index number of its own choice.
The collection is indexed using BINARY_INTEGER values, which do not need to be consecutive.
Index can besparse or dense.
3. Syntax of PL/SQL Tables
The syntax is given below:
Step-1:
Step-2:
Variable of type Table_type_name
Page | 92
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
BEGIN
loop
job_tab(counter) :=designation; -- Assigning designation variable to first index of job_tab
dbms_output.put_line (job_tab(counter));
counter:=counter+1;
exit when counter >10;
End loop;
END;
Explanation:
Value of local variable Designation is assigned to every index of PL/SQL Table i-e job_tab
Output of the Program
Prog
Prog
Prog
Prog
Prog
Prog
Prog
Prog
Prog
Prog
Prog
Page | 93
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
NEXT |
DELETE[(index[, index])]
EXISTS(index) |
COUNT |
NEXT(index) |
PRIOR(index)}
These are PL/SQL table attributes, which can be appended to the name of a PL/SQL table. FIRST
and LAST return the first and last (smallest and largest) index numbers in a PL/SQL table. If the
PL/SQL table is empty, FIRST and LAST return nulls. If the PL/SQL table contains only one
element, FIRST and LAST return the same index number.
Next
NEXT(n) returns the index number that succeeds index n in a PL/SQL table. Parameter is
required in executing next attribute. If n has no successor, NEXT(n) returns a null.
7. PL/SQL Table and Count Attribute
Count is a numeric attribute which return total number of index created. In other words,
COUNT returns the number of elements that a PL/SQL table contains and it is useful because
index are not sequential by default.
Page | 94
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
c3 c2;
counter number(10):=0;
Begin
for i in c1 loop
counter: =counter+2;
c3(counter):=[Link];
dbms_output.put_line (c3(counter));
End loop;
End;
Explanation:
A cursor is declared to fetch all those ename where salary < 3000. Then PL/SQL Table c2 is
declared to hold ename type data and in last step c3 is declared of c2 type. In the begin
section for loop is used to process cursor, now the counter of PL/SQL is having increment of 2
instead of 1 i-e index in c3 are created with gap of 2 not 1; this is possible in PL/SQL . Value
from cursor is coped into PL/SQL Table and is displayed in next step.
Output of the Program
Special
Statement processed.
Page | 95
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
End if;
b:=b+1;
End loop;
End;
Explanation:
The code is extension to previous example, after copying data in the PL/SQL table c3, in the
while loop values from the PL/SQL are displayed but since index are not consecutives and
[Link] (b) will return true if index exists at bth location otherwise it will return false and IF
will be evaluated to false. For every true value of [Link] (b) respective value will be
displayed on screen.
Write a PL/SQL block to load all the Employee names into PL/SQL Table and copy the values in
another PL/SQL Table before deleting those values from first PL/SQL Table
DECLARE
cursor c1 is select ename from emp;
type c2 is table of [Link]%type index by binary_integer;
c3 c2;
c4 c2;
counter number(10):=0;
b number(10):=0;
Begin
for i in c1 loop
counter :=counter+2;
c3(counter):=[Link];
--dbms_output.put_line (c3(counter));
End loop;
dbms_output.put_line ('Value of counter : ' || counter);
dbms_output.put_line ([Link]());
while (b<counter) loop
if [Link](b) then
dbms_output.put_line ('Value exists at Index : '|| b);
c4(b):=c3(b);
[Link](b);
dbms_output.put_line ('Value is deleted at Index '|| b);
dbms_output.put_line ('Value copied in new PL/SQL Table '|| c4(b));
Page | 96
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
End if;
b:=b+1;
End loop;
End;
Scenario
Write a PL/SQL block to load all the Employee names into PL/SQL Table and insert the values
into another table along with employee number and currentdate
DECLARE
cursor c1 is select ename from emp;
type c2 is table of [Link]%type index by binary_integer;
c3 c2;
c4 c2;
counter number(10):=0;
b number(10):=0;
Begin
for i in c1 loop
counter :=counter+2;
c3(counter):=[Link];
--dbms_output.put_line (c3(counter));
End loop;
dbms_output.put_line ('Value of counter : ' || counter);
dbms_output.put_line ([Link]());
while (b<counter) loop
if [Link] (b) then
insert into history values (b,c3(b),sysdate());
dbms_output.put_line ('Row is inserted using PL/SQL Table');
End if;
b:=b+1;
End loop;
End;
Page | 97
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
1. What is Record?
A record is a group of related data items stored in fields, each with its own name and data-type.
Suppose a database have various data about an employee such as name, salary, and hire date.
These items are logically related but dissimilar in type. A record containing a field for each item
lets you treat the data as a logical unit. Thus, records make it easier to organize and represent
[Link] consist of different fields, similar to a row of a database table. A record is
a composite data type, which means that it can hold more than one piece of information, as
compared to a scalar data type, such as a number or string.
2. Types of Record
There are following three types of Records. Their details are coming below.
Table Base
Cursor Base
User Defined
3. Table Base
A table-based record, or table record, is a record whose structure (set of columns) is drawn
from the structure (list of columns) of a table. Each field in the record corresponds to and has
the same name as a column in the table. The fact that a table record always reflects the current
structure of a table makes it useful when managing information stored in that table.
4. Implementing Table-based Records – I
Declare
emp_rec emp%rowtype;
Begin
select * into emp_rec from emp where empno=7369;
dbms_output.put_line (emp_rec.ename || ' ' || emp_rec.job);
Exception
when no_data_found then
dbms_output.put_line('No matching record found');
End;
Page | 98
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
emp_rec.ename := 'Consultant';
emp_rec.mgr := 7369;
emp_rec.hiredate := sysdate;
emp_rec.sal := 2000;
emp_rec.comm := NULL;
emp_rec.deptno := 10;
INSERT INTO emp
VALUES emp_rec;
dbms_output.put_line('Record base insertion is done');
END;
6. Cursor-based Records
A cursor-based record, or cursor record, is a record whose structure is drawn from the SELECT
list of a cursor. RowType in used in Oracle to create Cursor based records. You could declare a
cursor record with the same syntax as a table record, but you don't have to match a table's
structure. A SELECT statement creates a "virtual table" with columns and expressions as the list
of columns. A record based on that SELECT statement allows you to represent a row from this
virtual table in exactly the same fashion as a true table record.
7. Implementing Cursor -based Records – I
Scenario
Write a PL/SQL block which should look for first occurrence of employee either with
designation of CLERK or salary greater than 3000. Program should exit after this displaying
success message.
Solution
Declare
cursor c1 is select * from emp;
c2 c1%rowtype;
Begin
open c1;
loop
fetch c1 into c2;
if [Link] > 2000 or [Link]='CLERK' then
dbms_output.put_line ('Value is matched');
exit
End if;
exit when c1%notfound;
End loop;
End;
Page | 99
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Value is matched
End loop;
End;
Write a PL/SQL block to display the information of first 5 employees who are working as MAN in
their ename
Solution
Declare
type emp_rec is RECORD (empno [Link]%type, ename [Link]%type, sal
[Link]%type);
emp_rec_val emp_rec;
cursor c1 is select empno, ename, sal from emp where job like ('%MAN%');
Begin
open c1;
loop
fetch c1 into emp_rec_val;
dbms_output.put_line (emp_rec_val.ename || emp_rec_val.sal );
End loop;
End;
Page | 101
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
End;
Page | 102
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
1. What is Sub-Program?
A PL/SQL subprogram is a named PL/SQL block that can be invoked with a set of parameters. A
subprogram created to perform a particular task. These subprograms are combined to form
larger programs. This is basically called the 'Modular design'. Subprograms can either be
created at schema level, inside a package, or inside a PL/SQL block (which can be another
subprogram).
2. What is Procedure?
Procedure is a database object and a type of subprogram which is created to perform a certain
task. Such task can be called multiple times to avoid repetition and have efficiency. Procedure is
a subprogram that can take parameters and be called. Generally, you use a procedure to
perform an action. A procedure has two parts: the specification and the body.
3. Details of Procedure
Programmers can specify the name of the procedure, its parameters, its local variables, and the
BEGIN-END block that contains its code and handles any exceptions. You can specify whether
the procedure executes using the schema and permissions of the user who defined it, or the
user who calls it. It can receive zero or more parameters as an input and it can return value to
the calling environment but the returning value is optional. Summarizing:
Procedure can performs one or more tasks
Procedure may or may not return value
Procedures are normally used for executing business logic.
BEGIN
< procedure_body >
END procedure_name;
As mentioned above it can be called multiple times and different ways are available to compile,
debug and run the procedure.
Page | 103
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
END;
/
Output of the Program:
Procedure Created
Step-2:
Begin
first_proc;
End;
Hello World.
6. Debugging the Procedure
Procedure is compiled and executed separately. Data Dictionary can be used to identify errors
CREATE OR REPLACE PROCEDURE first_proc
AS
BEGIN
dbms_output.put_line('Hello World!);
END;
/
Output of the Program:
To view Errors user_errors data dictionary is to be browsed as below to find out error:
Page | 104
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
7. Implementing Procedure – I
CREATE OR REPLACE PROCEDURE name_proc
AS
cursor c1 is select * from emp where ename like ('%AK%');
c2 c1%rowtype;
BEGIN
loop
fetch c1 into c2;
dbms_output.put_line ([Link]);
exit when c1%notfound;
end loop;
END name_proc;
Output of the Program:
Procedure Created
/
Begin
Name_proc;
End;
8. Implementing Procedure – II
CREATE OR REPLACE PROCEDURE name_proc
AS
cursor c1 is select ename from emp where ename like ('%AK%');
c2 c1%rowtype;
BEGIN
loop
fetch c1 into c2;
dbms_output.put_line ([Link]);
exit when c1%notfound;
end loop;
END name_proc;
/
Calling the Procedure:
Begin
Name_proc;
Page | 105
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
End;
Where,
Write a PL/SQL procedure to find minimum among two values passed to the procedure.
Program should display the value of minimum value returned.
DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x; --
ELSE
z:= y;
END IF;
END;
Page | 106
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c); -- Parameter c will received value assigned to x inside procedure .
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
/
Explanation:
Since X is OUT type parameter, value to be return from procedure is copied into x
Output of the Program
Minimum of (23, 45): 23
Write a PL/SQL procedure to adjust the salary of the employee by percentage of the salary
provided at run-time. The procedure should return name of the employee which get updated
salary. Procedure will receive employeeid and % of salary to be updated.
CREATE OR REPLACE PROCEDURE adjust_salary(
in_employee_id IN [Link]%TYPE,
in_percent IN NUMBER, employeename out varchar2
) IS
BEGIN
-- update employee's salary
UPDATE emp
SET sal = sal + sal * in_percent / 100
WHERE empno = in_employee_id;
select ename into employeename from
emp where empno=in_employee_id;
END;
Output of the Program:
Procedure created.
Page | 107
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
percent number(10):=10;
name [Link]%type;
Begin
adjust_salary (id,percent,name);
dbms_output.put_line ('Name of Employee with updated salary ' || name );
End;
Output of the Program:
Write a PL/SQL procedure to display list of the employee names working in any particular
department. Procedure will receive deptno as input only.
create or replace PROCEDURE Get_emp_names (
Dept_num IN NUMBER) IS
Emp_name VARCHAR2(10);
CURSOR c1 IS
SELECT Ename FROM Emp
WHERE deptno = dept_num;
BEGIN
OPEN c1;
LOOP
FETCH c1 INTO Emp_name;
DBMS_OUTPUT.PUT_LINE(Emp_name);
EXIT WHEN C1%NOTFOUND;
END LOOP;
CLOSE c1;
END;
Output of the Program
Procedure created.
--Calling the Procedure
Begin
Page | 108
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Get_emp_names (10);
End;
Output of the Procedure:
KING
CLARK
MILLER
Special
Special
Write a PL/SQL procedure to adjust the salary of the employee by percentage of the salary
provided at run-time. The procedure should return name and designation of the employee
which get updated salary. Procedure will receive employeeid and % of salary to be updated.
in_employee_id IN [Link]%TYPE,
IS
BEGIN
UPDATE emp
where empno=in_employee_id;
END;
Page | 109
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Explanation:
Multiple values to be send as output are copied from ename, job into employeename,
employeedesignation i-e both are OUT parameter type. In the calling environment OUT values
are received into name and desig variables which are locally defined PL/SQL variable.
Procedure created
Declare
id [Link]%type:=7369;
percent number(10):=10;
name [Link]%type;
Desig [Link]%type;
Begin
adjust_salary (id,percent,name, desig);
dbms_output.put_line ('Name of Employee with updated salary ' || name);
dbms_output.put_line ('Employee Designation : ' || desig);
End ;
Page | 110
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
1. What is Function?
Function is a database object and a type of subprogram which is created to perform a certain
task. A function is a named PL/SQL Block which is similar to a procedure. The major difference
between a procedure and a function is, a function must always return a value, but a procedure
may or may not return a value. The tasks performed by the function can be called multiple
times to avoid repetition and have efficiency .
2. Details of Function
The further details about function are as follows:
It can receive zero or more parameters as an input.
It can return value to the calling environment.
Returning value is Mandatory. In other words, Procedure may or may not return value
whereas function should return one value
Function are normally used for computation.
3. Function vs. Procedure
In Function vs. Procedure comparison, there are following points:
Both are Database Objects.
Both can receive one or more parameters
Procedure can performs one or more tasks whereas function performs a specific task.
Procedure may or may not return value whereas function should return one value.
Functions are normally used for computation whereas procedures are normally used for
executing business logic.
4. Syntax of Creating PL/SQL Function
The syntax to create PL/SQL function is given below:
CREATE [OR REPLACE] FUNCTION function_name [ (parameter [,parameter]) ]
RETURN return_datatype
BEGIN
< function_body >
Return value
END function_name;
Again,
It can be called multiple times
It must return a value
Page | 111
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
END;
/
Output of the Program:
Function created.
Calling a Function:
DECLARE
c number(2);
BEGIN
c := totalemployees(); dbms_output.put_line('Total no. of Employees: ' || c);
END;
/
Output of the Program:
Page | 112
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
/
Output of the Program:
7. Dropping a Function
A function is deleted with the DROP FUNCTION statement. Function name will be deleted from
data dictionary automatically. The syntax to a drop a function is:
DROP FUNCTION function_name;
Where,
Function_name is the name of the function that you wish to drop.
8. Function and IN & OUT parameters
There are three type of parameter type in Functions and Procedures. IN and OUT types are
already discussed in the Procedure section. Third parameter type is INOUT. Parameter type
INOUT can behave as both IN and OUT simultaneously meaning it can used to passed value into
the function and same parameter can be used to write out (returning value) value by function
9. Implementing Function using IN Parameter – I
CREATE or replace FUNCTION Ask_salary(emp_no IN NUMBER)
RETURN NUMBER
IS emp_sal NUMBER(11,2);
BEGIN
SELECT sal
INTO emp_sal
FROM emp
WHERE empno=emp_no;
RETURN(emp_sal);
END;
Explanation:
This function will receive emo_no as input and will return salary of the employee to the calling
environment. The value of emp_no can’t be changed in the function body because parameter
type of emp_no is IN.
Page | 113
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Function created.
Calling a Function:
Declare
salary [Link]%type;
Begin
salary:=ask_salary(7369);
dbms_output.put_line(salary);
End;
Output of the Program:
170701.96
END;
Explanation:
This function will receive emo_no as input and will return ename and return salary of the
employee to the calling environment. This function is returning multiple values using Function.
The value of emp_no can’t be changed in the function body because parameter type of
emp_no is IN.
Calling a Function:
Declare
salary [Link]%type;
emp_name varchar2(30);
Begin
salary:=ask_salary(7369, emp_name);
Page | 114
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
dbms_output.put_line(salary ||emp_name);
dbms_output.put_line(emp_name);
End;
DECLARE
retval VARCHAR2(20);
ioval VARCHAR2(20) := 'Going in';
BEGIN
DBMS_OUTPUT.put_line('In: ' || ioval);
retval := inout_fn(ioval);
DBMS_OUTPUT.put_line('Out: ' || ioval);
DBMS_OUTPUT.put_line('Return: ' || retval);
END;
/
Explanation:
In the function outparm is having INOUT parameter type i-e value can be updated during the
function body and the same parameter can be used to return value to the calling
environment. Ioval is passed from the calling environment, in the body of the function ioval is
updated to ‘Coming out’ and is same value is written back to outparam i-e this is only possible
when parameter type is INOUT both.
Output of the Program
In: Going in
Page | 115
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Write a PL/SQL Procedure to add new employee in the Database, Name of Employee and Salary
will be passed as parameter to procedure and date of hiring will be inserted in addition to it. A
function should return 1 if there is at least one hiring in last 1 month otherwise it should return
0
Solution:
END hire_employee;
Create or replace function check_employee_status
return number as
total number(10):=0;
Begin
select count(*) into total from emp where hiredate = sysdate - 30;
if total>1 then
return 1;
else return 0;
End if;
End check_employee_status;
Declare
name varchar2(15):='KAMRAN';
salary_emp number(10):=15000;
Result number(2);
Begin
hire_employee (name, salary_emp);
result:= check_employee_status();
if (result=1) then
dbms_output.put_line ('There is hiring in last month');
Else
dbms_output.put_line ('There is No hiring in last month');
End if;
End;
Page | 116
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
A row trigger is fired for each row that is affected by the triggering statement. For example, if
an UPDATE statement updates multiple rows of a table, a row trigger is fired once for each row
affected by the UPDATE statement. If a triggering statement affects no rows, a row trigger is
not executed.
Statement Level
in any case
A statement trigger is fired once on behalf of the triggering statement, regardless of the
number of rows affected by the associated DML, even if no rows are affected. For example, if a
DELETE statement deletes several rows from a table, a statement-level DELETE trigger is fired
only once.
Page | 117
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Before: BEFORE triggers run the trigger action before the triggering statement is run. It is
execute before the execution of DML statement.
After: AFTER triggers run the trigger action after the triggering statement is run. Trigger is
executed after execution of associated DML statement.
Declare
BEGIN
sql statements
END;
Write a Trigger to store the previous values of the product if there change in any price of the
product. History table should be maintained to keep record of the previous values just like a
shadow table.
drop table product;
CREATE TABLE product
(product_id number(5),
product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );
Page | 118
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
END; /
When UPDATE is issued as follow:
Page | 119
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Write a Trigger which should enforce referential integrity constraint while inserting data in Emp
table. Insert or Updating in Emp table should ensure the corresponding deptno in dept table
should existence prior to DML statement, if there is no matching parent record in Dept table
then DML should not be executed.
END;
Output of the Program
Trigger created.
Page | 120
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
When Row is inserted into Emp table with invalid deptno (90) as below:
Write a Trigger which should be used to track every insert statement i-e not the data which is
inserted. Log table will provide the count along with data / time of every insertion on Emp
Table.
Page | 121
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
Through this all the entries from the Data Dictionaries will be removed.
Page | 122
Virtual University of Pakistan
Join VU Group: [Link]
Handouts
1. What is package?
It is Database Object which group together different Database Objects. groups logically related
PL/SQL types, variables, constants, subprograms, cursors, and exceptions. A package is
compiled and stored in the database. Packages offer several advantages: modularity, easier
application design, information hiding, added functionality, and better performance. Packages
let you encapsulate logically related types, items, and subprograms in a named PL/SQL module.
Each package is easy to understand, and the interfaces between packages are simple, clear, and
well defined. This aids application development.
2. Parts of package
There are following two parts of a Package:
Package Specification: The specification is the interface to your applications; it declares the
types, variables, constants, exceptions, cursors, and subprograms available for use. The spec
holds public declarations, which are visible to the application
Package Body: The body fully defines cursors and subprograms, and so implements the spec.
The body holds implementation details and private declarations, which are hidden from your
application.
3. Syntax of Package
Syntax for Creating Package is as follows:
Step-1:
Again,
Page | 123
Virtual University of Pakistan
Join VU Group: [Link]