PL/SQL is Oracle's procedural language extension to SQL,
the non-procedural relational database language.
With PL/SQL, you can combine the data manipulating power
of SQL with the data processing power of procedural
languages.
CS 262: DBMS Lab
PL/SQL blocks can be divided into two groups:
1. Named and
2. Anonymous.
Named blocks are used when creating subroutines. These
subroutines are procedures, functions, and packages.
The subroutines can be stored in the database and
referenced by their names later on.
Anonymous PL/SQL blocks do not have names. As a result,
they cannot be stored in the database and referenced later.
CS 262: DBMS Lab
PL/SQL blocks contain three sections
1. Declare section
2. Executable section and
3. Exception-handling section.
The executable section is the only mandatory section of the
block.
Both the declaration and exception-handling sections are
optional.
CS 262: DBMS Lab
PL/SQL block has the following structure:
DECLARE
Declaration statements
BEGIN
Executable statements
EXCETION
Exception-handling statements
END ;
CS 262: DBMS Lab
The declaration section contains definitions of PL/SQL
identifiers such as variables, constants, cursors and so on.
Example
DECLARE
v_first_name VARCHAR2(35) ;
v_last_name VARCHAR2(35) ;
v_counter NUMBER := 0 ;
CS 262: DBMS Lab
The executable section contains executable statements that
allow you to manipulate the variables that have been
declared in the declaration section.
BEGIN
SELECT first_name, last_name
INTO v_first_name, v_last_name
FROM student
WHERE student_id = 123 ;
DBMS_OUTPUT.PUT_LINE
(‘Student name :’ || v_first_name ||‘ ’|| v_last_name);
END;
CS 262: DBMS Lab
The exception-handling section contains statements that are
executed when a runtime error occurs within a block.
Runtime errors occur while the program is running and
cannot be detected by the PL/SQL compiler.
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE
(‘ There is no student with student id 123 ’)
END;
CS 262: DBMS Lab
Open text editor using ed in SQL*Plus
Type the program
Save the program with .sql extension in your user
To execute a PL/SQL program, type the following command
at the SQL prompt:
SQL> @Z:\plsql\DisplayAge.sql
CS 262: DBMS Lab
Like other programming languages, PL/SQL provides a
procedure (i.e. PUT_LINE) to allow the user to display the
output on the screen. For a user to able to view a result on
the screen, two steps are required.
First, before executing any PL/SQL program, type the
following command at the SQL prompt (Note: you need to
type in this command only once for every SQL*PLUS
session):
SQL> SET SERVEROUTPUT ON;
or put the command at the beginning of the program, right
before the declaration section.
CS 262: DBMS Lab
Second, use DBMS_OUTPUT.PUT_LINE in your executable
section to display any message you want to the screen.
Syntax for displaying a message:
DBMS_OUTPUT.PUT_LINE(<string>);
in which PUT_LINE is the procedure to generate the output
on the screen, and DBMS_OUTPUT is the package to which
the PUT_LINE belongs.
DBMS_OUTPUT.PUT_LINE(‘My age is ‘ || num_age);
CS 262: DBMS Lab
Variables are
Used to store numbers, character strings, dates, and other data values
Avoid using keywords, table names and column names as variable
names
Must be declared with data type before use:
▪ variable_name data_type_declaration;
CS 262: DBMS Lab
Reference variables directly reference a specific database
field or record and assume the data type of the associated
field or record
%TYPE: same data type as a database field
%ROWTYPE: same data type as a database record
t_eno emp.eno%type;
t_emp emp%rowtype;
CS 262: DBMS Lab
DECLARE
d dept%ROWTYPE;
BEGIN
SELECT deptno,dname,loc INTO d FROM dept WHERE
deptno=10;
DBMS_OUTPUT.PUT_LINE(d.dname);
END;
CS 262: DBMS Lab
SQL*Plus allows a PL/SQL block to receive input information
with the help of substitution variables.
Substitution variables cannot be used to output the values
because no memory is allocated for them.
Substitution variables are usually prefixed by the
ampersand(&) character.
v_student_id NUMBER := &sv_student_id;
When this example is executed, the user is asked to provide a
value for the student ID.
CS 262: DBMS Lab
Assigns a value to a variable
variable_name := value;
Value can be a literal/another variable:
current_s_first_name := 'John';
current_s_first_name := s_first_name;
CS 262: DBMS Lab
Sequential processing
Processes statements one after another
Decision control structures
Alter order in which statements execute
Based on values of certain variables
Logical flow of statements within the PL/SQL block can be
changed with a number of control structures.
Two types of PL/SQL control structures:
conditional constructs with the IF statement
LOOP control structures
CS 262: DBMS Lab
Syntax
IF condition1 THEN
commands that execute if condition1 is TRUE;
ELSIF condition2 THEN
commands that execute if condition2 is TRUE;
ELSIF condition3 THEN
commands that execute if condition3 is TRUE;
...
ELSE
commands that execute if none of the
conditions are TRUE;
END IF;
CS 262: DBMS Lab
Simple IF statement:
Set the manager ID to 22 if the employee name is Osborne.
IF v_ename = 'OSBORNE' THEN v_mgr := 22;
END IF;
Set the job title to Salesman, the department number to 35, and the
commission to 20% of the current salary if the last name is Miller
IF v_ename = 'MILLER' THEN
v_job := 'SALESMAN';
v_deptno := 35;
v_new_comm := sal * 0.20;
END IF;
CS 262: DBMS Lab
IF-THEN-ELSE Statements
Set a flag for orders where there are fewer than five days between order
date and ship date.
IF v_shipdate - v_orderdate < 5 THEN
v_ship_flag := 'Acceptable';
ELSE
v_ship_flag := 'Unacceptable';
END IF;
CS 262: DBMS Lab
Nested IF Statement
For a given value, calculate a percentage of that value based
on a condition.
IF v_start > 100 THEN
v_start := 2 * v_start;
ELSIF v_start >= 50 THEN
v_start := .5 * v_start;
ELSE
v_start := .1 * v_start;
END IF;
CS 262: DBMS Lab
Any arithmetic expression containing a null value evaluates
to NULL.
Concatenated expressions with null values treat null values
as an empty string.
NULL acts as False
The IS NULL condition evaluates to TRUE only if the variable
it is checking is NULL.
CS 262: DBMS Lab
Loops repeat a statement or sequence of statements
multiple times.
There are three types of loop statements:
Basic loop
FOR loop
WHILE loop
CS 262: DBMS Lab
Syntax
LOOP
statement1;
...
EXIT [WHEN condition];
END LOOP;
A basic loop can contain multiple EXIT statements.
CS 262: DBMS Lab
DECLARE
v_ordid item.ordid%TYPE := 601;
v_counter NUMBER(2) := 1;
BEGIN
LOOP
INSERT INTO item(ordid, itemid)
VALUES(v_ordid, v_counter);
v_counter := v_counter + 1;
EXIT WHEN v_counter > 10;
END LOOP;
END;
CS 262: DBMS Lab
Syntax
FOR counter in [REVERSE]
lower_bound..upper_bound LOOP
statement1;
statement2;
...
END LOOP;
Do not declare the counter; it is declared implicitly.
The lower bound and upper bound of the loop range can be
literals, variables, or expressions, but must evaluate to
integers
Do not reference the counter as the target of an assignment.
An error message rises if you do so.
CS 262: DBMS Lab
DECLARE
v_ordid item.ordid%TYPE := 601;
BEGIN
FOR i IN 1..10 LOOP
INSERT INTO item(ordid, itemid)
VALUES(v_ordid, i);
END LOOP;
END;
CS 262: DBMS Lab
Syntax
WHILE condition LOOP
statement1;
statement2;
...
END LOOP;
CS 262: DBMS Lab
DECLARE
v_count NUMBER(2) := 1;
num_depts NUMBER := &num_depts ;
BEGIN
WHILE v_count <= num_depts LOOP
INSERT INTO dept(deptno,dname)
VALUES (v_count, &v_dept_name);
v_count := v_count + 1;
END LOOP;
COMMIT;
END;
CS 262: DBMS Lab
A cursor is a temporary work area created in the system
memory when an SQL statement is executed.
This temporary work area is used to store the data retrieved
from the database, and manipulate this data.
A cursor can hold more than one row, but can process only
one row at a time.
There are two types of cursors in PL/SQL:
Implicit cursors:
Explicit cursors:
Both implicit and explicit cursors have the same
functionality, but they differ in the way they are accessed.
CS 262: DBMS Lab
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.
Oracle provides few attributes called as implicit cursor
attributes to check the status of DML operations.
CS 262: DBMS Lab
%notfound Identifies whether the fetch executed
on the cursor did not return a row.
%rowcount Identifies the number of rows that were
processed by this cursor.
%found Identifies whether the fetch executed
on the cursor return a row.
%isopen Identifies whether the cursor referred
to is opened and ready for use.
CS 262: DBMS Lab
DECLARE var_rows number(5);
BEGIN
UPDATE employee SET salary = salary + 1000;
IF SQL%NOTFOUND THEN
dbms_output.put_line('None of the salaries were
updated');
ELSIF SQL%FOUND THEN
var_rows := SQL%ROWCOUNT;
dbms_output.put_line('Salaries for ' || var_rows ||
'employees are updated');
END IF;
END;
CS 262: DBMS Lab
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.
CS 262: DBMS Lab
DECLARE
myempid number;
mysal number;
CURSOR emp_crsr IS
SELECT empid, salary FROM employee;
BEGIN
OPEN emp_crsr;
LOOP
FETCH emp_crsr INTO myempid, mysal;
EXIT WHEN emp_crsr%NOTFOUND;
if myempid = 10 or myempid = 30 then
UPDATE employee SET salary = mysal + 5000 WHERE empid = myempid;
else
UPDATE emp SET salary = mysal + 1111 WHERE empid = myempid;
end if;
END LOOP;
END;
CS 262: DBMS Lab
Named system exceptions.
Named programmer-defined exceptions.
Unnamed system exceptions.
Unnamed programmer-defined exceptions.
CS 262: DBMS Lab
The exceptions which are already given names by PL/SQL
are declared in the STANDARD package in PL/SQL.
You do not have to declare them in your own programs.
Example
EXCEPTION
WHEN CURSOR_ALREADY_OPEN
THEN
CLOSE my_cursor;
END;
CS 262: DBMS Lab
CURSOR_ALREADY_OPEN
DUP_VAL_ON_INDEX
INVALID_CURSOR
NO_DATA_FOUND
TOO_MANY_ROWS
ZERO_DIVIDE
CS 262: DBMS Lab
Declare
sal emp.salary%type;
BEGIN
select salary into sal from emp where eno = 1;
EXCEPTION
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE(‘MORE THAN ONE ROW SELECTED…’ );
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(‘NO EMPLOYEE EXISTS WITH ENO= 1’ );
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(‘OTHER TYPE OF ERROR HAS OCCURED…’ );
END;
CS 262: DBMS Lab
Errors that are specific to the application program need to be
handled by this type of exceptions.
For User-Defined Exception, the programmer should
Name the Exception by declaring it in the declaration section of
PL/SQL block.
Check for the error and raise the exception
Handle the exception
CS 262: DBMS Lab
Declare
negative_salary EXCEPTION;
sal emp.salary%type;
BEGIN
select salary into sal from emp where eno = 1;
if (sal < 0) then
RAISE negative_salary;
else
DBMS_OUTPUT.PUT_LINE(‘Salary =‘||sal);
end if;
EXCEPTION
WHEN negative_salary THEN
DBMS_OUTPUT.PUT_LINE(‘INVALID SALARY…’ );
UPDATE EMP SET SALARY = 0 WHERE ENO = 1;
END;
CS 262: DBMS Lab