DBMS-UNIT 4
DBMS-UNIT 4
DBMS-UNIT 4
SQL is the natural language of the DBA but suffers from inherent disadvantages. They are
It does not have procedural capabilities
SQL statements are passed to the oracle engine one at a time. This decreases the
processing speed in a multi-user environment
SQL has no facility of programmed handling of error messages.
Advantages of PL/SQL
1. PL/SQL is a development tool that not only supports SQL data manipulation but also
provides facilities for condition checking, branching and looping
2. PL/SQL sends the entire block of SQL code to oracle engine. As the entire block of SQL
code is passed to Oracle engine at one time for execution, all the changes made to the
data in the table are done or undone in one go.
3. PL/SQL facilitates the displaying of user-friendly messages when errors are
encountered.
4. PL/SQL allows declaration and use of variables in blocks of code. The variables are
used to store intermediate results of a query for later processing
5. PL/SQL all sorts of calculations can be done efficiently and quickly
6. Applications written in PL/SQL are portable to any computer hardware system and
operating system.
The Generic PL/SQL block
A single PL/SQL code block consists of a set of SQL statements.This block has to be logically
grouped together for the engine to recognize it as singular block of code.
A PL/SQL block has a definite structure, which can be divided into sections. The sections of
PL/SQL block are
a. Declare section
b. Master begin…end section
Example:
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
PL/SQL Execution Environment:
The PL/SQL engine accepts any valid PL/SQL block as input
PL/SQL engine resides in the Oracle engine. Oracle engine can process both SQL statements
and PL/SQL blocks.These blocks are sent to the PL/SQL engine, where the procedural
statements are executed. SQL statements are sent to the SQL executor in the Oracle engine.
The call to the oracle engine needs to be made only once to execute any number of SQL
statements if these SQL statements are bundled inside a PL/SQL block
Words used in PL/SQL blocks are called lexical units. Blank spaces can freely be inserted
between lexical units in a PL/SQL block.
A literal is a numeric or character string used to represent itself. A numeric literal can be a
integer or float value. E.g. 5, -20, 29.6. A string literal is a set of two or more characters
enclosed in single quotes.E.g. ‘Hello’, ‘Hi’.A character literal is a single character enclosed in
single quotes. E.g. ‘Y’, ‘N’, ‘m’. Boolean literals or logical literals are predetermined
constants. The values these literals can hold are TRUE, FALSE, NULL
PL/SQL Data types
The default data types that can be declared in PL/SQL are
1. Number – Numeric values, on which arithmetic operations are performed.
2. Character – Alphanumeric values that represent single characters or strings of
characters.
3. Boolean – Logical values, on which logical operations are performed.
4. Date/time – Date and time.
The above data types can have NULL values.
5. The % type attribute is used to declare variables based on the definitions of
columns in a table. It helps to declare a variable or constant to have same data
type as that of a column declared in a table.
Variables
A variable in PL/SQL is a named variable. A variable name must begin with a character and
can be followed by a maximum of 29 characters. Reserved words cannot be used as variable
names unless enclosed within double quotes.
A blank space cannot be embedded in a variable name. variable names are not case
sensitive. Variables are separated from each other by a comma.
Values can be assigned to variables in two ways:
1. Using the assignment operator :=
2. Selecting or fetching table data values into variables
Constants: A constant is declared in the same way as how a variable is declared. The only
difference is that we use a keyword constant and a value is assigned to it immediately.
Thereafter no further assignments can be made.
Logical Comparisons
Comparisons in PL/SQL can be made using Boolean expressions. A Boolean expression
consists of variables separated by relational operators{<,>,<=,>=,<>}.
A logical expression is a combination of two or more Boolean expressions separated by
logical operators{AND,OR, NOT}.
A Boolean expression always evaluates to TRUE, FALSE or NULL.
Example:
set serveroutput on
declare
x number(2);
y number(2);
begin
x:=&x;
y:=&y;
if x>y then
dbms_output.put_line (x || 'is bigger');
else
dbms_output.put_line (y || 'is bigger');
end if;
end;
Output:
Enter value for x: 35
Enter value for y: 25
35is bigger
PL/SQL procedure successfully completed.
Iterative control
Iterative control indicates the ability to repeat sections of code. A loop marks the
sequence of statements that has to be repeated. Iterative control Statements are used when
we want to repeat the execution of one or more statements for specified number of times.
There are three types of loops in PL/SQL:
• Simple Loop
• While loop
• For loop
Simple Loop
A Simple Loop is used when a set of statements is to be executed at least once before
the loop terminates. An EXIT condition must be specified in the loop, otherwise the loop will
get into an infinite number of iterations. When the EXIT condition is satisfied the process
exits from the loop.
While loop
A WHILE LOOP is used when a set of statements has to be executed as long as a condition is
true. The condition is evaluated at the beginning of each iteration. The iteration continues
until the condition becomes false.
FOR Loop
A FOR LOOP is used to execute a set of statements for a predetermined number of times.
Iteration occurs between the start and end integer values given. The counter is always
incremented by 1. The loop exits when the counter reachs the value of the end integer.
Syntax of FOR LOOP is:
FOR variable IN [REVERSE] start…end
LOOP
<action>
END LOOP;
Example:
set serveroutput on
declare
i number;
n number;
f number:=1;
begin
n:=&n;
for i in 1..n
loop
f:=f*i;
end loop;
dbms_output.put_line('Factorial is '|| f);
end;
Output:
Enter value for n: 5
Factorial is 120
PL/SQL procedure successfully completed.
CURSORS
The Oracle engine uses a work area for its internal processing in order to execute an SQL
statement. This work area is private to SQL operations and is called a Cursor.
The data that is stored in the cursor is called the Active Data Set. The size of the cursor in
the memory is the size required to hold the number of rows in the active data set. Oracle has
a predefined area in the main memory set aside, within which cursors are opened.
A cursor contains information on a select statement and the rows of data accessed by
it. A cursor can hold more than one row, but can process only one row at a time.
Cursors are classified depending on the circumstances under which they are
opened.Both implicit and explicit cursors have the same functionality, but they differ in the
way they are accessed
Implicit cursors
If the oracle engine opened a cursor for its internal processing, it is known as implicit
cursor. These are created by default when DML statements like, INSERT, UPDATE, and
DELETE statements are executed. They are also created when a SELECT statement that
returns just one row is executed.
Implicit Cursor Attributes:
AttributesReturn Value Example
%FOUND The return value is TRUE, if the DML SQL%FOUND
statements like INSERT, DELETE and
UPDATE affect at least one row and if
SELECT ….INTO statement return at least one
row.
The return value is FALSE, if DML statements
like INSERT, DELETE and UPDATE do not
affect row and if SELECT….INTO statement
do not return a row.
%NOTFOUND The return value is FALSE, if DML statements SQL%NOTFOUND
like INSERT, DELETE and UPDATE at least
one row and if SELECT ….INTO statement
return at least one row.
The return value is TRUE, if a DML statement
like INSERT, DELETE and UPDATE do not
affect even one row and if SELECT ….INTO
statement does not return a row.
%ROWCOUNT Return the number of rows affected by the SQL%ROWCOUNT
DML operations INSERT, DELETE, UPDATE,
SELECT
Example: Consider the PL/SQL Block that uses implicit cursor attributes as shown below:
/*increase the salary of all employees by 1000*/
DECLARE var_rows number(5);
BEGIN
UPDATE employ
SET salary = salary + 1000;
IF SQL%NOTFOUND THEN
dbms_output.put_line('None of the salaries where updated');
ELSIF SQL%FOUND THEN
var_rows := SQL%ROWCOUNT;
dbms_output.put_line('Salaries for ' || var_rows || 'employees are updated');
END IF;
END;
Output:
Salaries for 7employees are updated
PL/SQL procedure successfully completed.
Explicit cursors
A cursor can be opened They must be created when you are executing a SELECT statement
that returns more than one row. Even though the cursor stores multiple records, only one
record can be processed at a time, which is called as current row.
When you fetch a row the current row position moves to next row. When individual
records in a table have to be processed inside a PL/SQL block explicit cursor is used. This
cursor will be declared and mapped to an SQL query in the declare section of the PL/SQL
block and used with the executable section of PL/SQL block.
The steps involved in using explicit cursor and manipulating data are
•Declare a cursor in the declare section of PL/SQL block
•Open the cursor
•Fetch the data from the cursor one row at a time into the memory variables
•Process the data that was fetched
•Exit from the loop after the processing is complete
•Close the cursor
Example:
DECLARE
CURSOR emp_cur IS
SELECT *
FROM employ
WHERE salary > 5000;
In the above example we are creating a cursor ‘emp_cur’ on a query which returns the
records of all the employees with salary greater than 5000.
Opening a cursor – Opening a cursor executes a query and creates an active data set that
contains all rows which meet the search criteria of the query. An open statement retrieves
the records from the table and places the records in the cursor
Syntax:
OPEN cursor_name;
Fetching records from the cursor – The fetch statement retrieves the rows from the active
data set into the memory variables declared in the PL/SQL block one row at a time. Each
time a fetch statement is executed, the cursor pointer is advances to the next row in the
active data set.
Syntax:
FETCH cursor-name INTO variable list;
Closing a cursor – The close statement disables the cursor and the active data set becomes
undefined. This will release the memory occupied by the cursor and the active data set.
Syntax:
CLOSE cursor-name;
General Form of using an explicit cursor is:
DECLARE
variables;
records;
create a cursor;
BEGIN
OPEN cursor;
FETCH cursor;
process the records;
CLOSE cursor;
END;
Example:
/*Display employee name and salary whose salary is more than 6000*/
SET SERVEROUTPUT ON
DECLARE
emp_rec employ%rowtype;
CURSOR emp_cur IS
SELECT *
FROM employ
WHERE sal > 6000;
BEGIN
OPEN emp_cur;
FETCH emp_cur INTO emp_rec;
dbms_output.put_line (emp_rec.ename || ' ' || emp_rec.sal);
CLOSE emp_cur;
END;
/
Output:
SQL> @EXPCUR.SQL
Gita 7000
PL/SQL procedure successfully completed.
Parameterized Cursors
Oracle permits the data that is retrieved from the table be allowed to change
according to need. The contents of parameterized cursor will constantly change depending
on the value that is passed as parameter. Since the cursor accepts user-defined values into
its parameters, thus changing the result set extracted, it is called parameterized cursor.
Declaring Parameterized cursor:
Syntax: CURSOR cursor_name IS <SELECT statement>;
Opening a Parameterized Cursor:
Syntax: OPEN cursor_name(value/variable/expression);
Example:/*DISPLAY DETAILS OF STUDENT WITH ROLLNUMBER */
SET SERVEROUTPUT ON
DECLARE
cursor c(no number) is select * from student
where rollno = no;
tmp student%rowtype;
BEGIN
FOR tmp IN c(14)
LOOP
dbms_output.put_line('ROLLNO: '||tmp.rollno);
dbms_output.put_line('STUDENT_Name: '||tmp.name);
dbms_output.put_line('TOTAL: '||tmp.total);
dbms_output.put_line('COURSE: '||tmp.course);
END Loop;
END;
/
Output:
ROLLNO: 14
STUDENT_Name: Gita
TOTAL: 145
COURSE: bca
PL/SQL procedure successfully completed
1. IN – indicates that the parameter will accept a value from the user
2. OUT – indicates that the parameter will return a value to the user
3. IN OUT - indicates that the parameter will either accept a value from the user or
return a value to the user
Example:
/*procedure */
CREATE or REPLACE PROCEDURE pro1(no in number,temp out student%rowtype)
IS
BEGIN
SELECT * INTO temp FROM student WHERE rollno = no;
END;
/
SQL> @proc1;
Procedure created.
SQL> ed sqlproc.sql
/*PL-SQL code for implementing procedure*/
SET SERVEROUTPUT ON
DECLARE
temp student%rowtype;
no number :=&no;
BEGIN
pro1(no,temp);
dbms_output.put_line(temp.rollno||' '|| temp.name||' '||temp.total);
END;
/
Output:
Enter value for no: 12
12 Sriram 235
PL/SQL procedure successfully completed.
Functions: 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. Here, return type in the header section defines
the return type of the function. The return data type can be any of the oracle data type like
varchar, number etc.
Syntax for creating a function:
CREATE OR REPLACE FUNCTION <function_name>
(<Argument> {IN }<data type>…)
RETURN return_datatype;
IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;
Example:
SQL> ED STUDFUN.SQL
/*create a function*/
CREATE or REPLACE FUNCTION STUDFUN(no in number) RETURN varchar2
IS
name varchar2(20);
BEGIN
select name into name from student where rollno = no;
return name;
END;
SQL> @STUDFUN.SQL;
Function created.
SQL> ed plfun.sql
ORACLE PACKAGES
A package is an Oracle object, which holds other objects within it. PL/SQL packages
are schema objects that groups logically related procedures, functions, constants,
variables and cursors. It is a way of creating generic, encapsulated and reusable code. A
package once written and debugged is compiled and stored in Oracle’s system tables held in
Oracle database. Packages contain PL/SQL blocks of code, which have been written to
perform some process entirely on their own. These PL/SQL blocks do not require any input
from other PL/SQL blocks of code.
Components of an Oracle Package:
A package has usually two components – specification and a body.
Package Specification:
The specification is the interface to the package. It just DECLARES the types,
variables, constants, exceptions, cursors, and subprograms that can be referenced from
outside the package. In other words, it contains all information about the content of the
package, but excludes the code for the subprograms. All objects placed in the specification
are called public objects. Any subprogram not in the package specification but coded in the
package body is called a private object.
Package specification contains
• Name of the package
• Names of the data types of any arguments
• This declaration is local to the database and global to the package
The syntax for package specification is as follows:
CREATE PACKAGE <package-specification-name> IS
<function declaration>
<procedure declaration >
END<package-specification-name>;
Package Body:
The body of a package contains the definition of the public objects that are declared
in the specification. The package body has the codes for various methods declared in the
package The CREATE PACKAGE BODY Statement is used for creating the package body. The
syntax for creating package body is as follows:
CREATE PACKAGE BODY <package-name> AS
<function definition >
<procedure definition>
END<package-name>;
Advantages of Packages
Packages offer the following advantages
• Packages enable organizing applications as efficient modules
• It allows granting of privileges efficiently
• They enable overloading of procedures and functions, if required
• They promote reusability of code
• They improve performance by loading multiple objects into the memory at once.
Creating a Package:
The first step in creating a package is to create its specification. The specification
declares the objects that are contained in the body of the package. A package can include
functions and procedures. After the specification is created, the body of the package needs
to be created. The body of the package is a collection of detailed definitions of the objects
that were declared in the specification.
Example:
Display the student name, course and total by implementing package
/*Creating package specification*/
SQL> ed sampkg
BEGIN
select name,course into temp1, temp2 from student where rollno = no;
dbms_output.put_line('Student Name:' || temp1);
dbms_output.put_line('Course Name:' || temp2);
END;
ERROR HANDLING IN PL/SQL
An exception handler is nothing but a code block in memory that will attempt to resolve the
current exception condition. The oracle engine can recognize every exception condition that
occurs in the memory. To handle very common and repetitive exception conditions, the
oracle engine uses Named Exception Handlers.
PL/SQL Errors are pre-defined and are automatically raised by Oracle whenever an error is
encountered. Each error is assigned a unique number and a message. In PL/SQL, a warning
or error condition is called an exception. Exceptions can be internally defined (by the run-
time system) or user defined.
Examples of internally defined exceptions include division by zero and out of
memory. Some common internal exceptions have predefined names, such as ZERO_DIVIDE
and STORAGE_ERROR. The other internal exceptions can be given names.
When an error occurs, an exception is raised. That is, normal execution stops and
control transfers to the exception-handling part of your PL/SQL block or subprogram.
Internal exceptions are raised implicitly (automatically) by the run-time system. User-
defined exceptions must be raised explicitly by RAISE statements, which can also raise
predefined exceptions. To handle raised exceptions, you write separate routines called
exception handlers.
Syntax:
EXCEPTION
WHEN<Exception Name> THEN
<User Defined Action to be carried out>
Oracle’s Named Exception Handlers
The Oracle engine has a set of predefined Oracle error handlers called Named
Exceptions. These error handlers are referenced by their names. Some of the pre-defined
Oracle named exception handlers are listed below
DUP_VAL_ON_INDEX Raised when an insert or update attempts to create two rows with
duplicate values in columns constrained by unique index
LOGIN_DENIED Raised when an invalid user name/password is used to log onto Oracle
NO_DATA_FOUND Raised when a select statement returns zero rows
NOT_LOGGED_ON Raised when PL/SQL issues an Oracle call without being logged onto
Oracle
PROGRAM_ERROR Raised when PL/SQL has an internal problem
TOO_MANY_ROWS Raised when a select statement returns more than one row
VALUE_ERROR Raised when the data type or data size is invalid
OTHERS Stands for all other exceptions not explicitly named
EXCEPTION
WHEN<Exception Name> THEN
<Action>
END;
User Defined Exception Handlers
User Defined Exception Handlers for Business Rule Validation
In commercial applications, data that is being manipulated needs to be validated
against business rules. If the data violates a business rule, the entire record must be
rejected. To trap business rules being violated the technique of raising user-defined
exceptions and then handling them is used.
User defined error conditions are declared in the DECLARE section of PL/SQL block.
In the executable part, a check for the condition is made. If the condition exists, the call to
the user defined exception is made using RAISE statement. The exception once raised is
then handled in the exception handling section of the PL/SQL code block.
Syntax:
DECLARE
<<Exception Name> Exception;
BEGIN
SQL statements;
IF <condition>THEN
RAISE <Exception Name>;
END IF;
EXCEPTION
WHEN <Exception Name> THEN {user-defined action}
END
Example:
SET SERVEROUTPUT ON
DECLARE
myex EXCEPTION;
i NUMBER;
BEGIN
FOR i IN (SELECT * FROM student)
LOOP
IF i.rollno = 15 THEN
RAISE myex;
END IF;
END LOOP;
EXCEPTION
WHEN myex THEN
dbms_output.put_line('ROLLNO is Filled Already');
END;
/