PLSQL Tutorial
PLSQL Tutorial
Learn he ba ic of PL/SQL
Be B
.da aba e a .c
PL/SQL T ial
PL/SQL is not a hard lang age to learn, and ith this t torial, o 'll be p and r nning q ickl ith
riting o r first PL/SQL program and mo ing on to more feat res of this lang age.
So, h sho ld o read this t torial hen there's a lot of other t torials, books, and ideos o t there?
● Yo 'll start riting o r first PL/SQL program er earl , before reading a ton of pages on
theor .
● It looks great.
Table of Contents
This t torial is broken do n into se eral chapters, each of hich co er a different area of PL/SQL.
Yo 'll start ith the basics and mo e on to more feat res of the lang age.
C 1: W PL/SQL, , PL/SQL .
In this chapter o 'll learn hat PL/SQL is and hat it's sed for and the basic str ct re of PL/SQL
code. Yo 'll also rite o r first PL/SQL program. We'll sho o ho to do this earl in the t torial so
o can get e perience riting PL/SQL code.
C 2: D , , , .
PL/SQL allo s for ariables to be created to hold data. We'll sho o ho to create ariables and
constants and ho to incl de them and reference them in o r PL/SQL code.
This chapter ill sho o ho to ork ith conditions in PL/SQL, hich are done sing IF THEN
ELSE statements. Yo 'll also learn ho to se the different kinds of loops.
C 4: P , , .
.Da aba eS a .c m
PL/SQL T ial
Proced res and f nctions are common objects that se PL/SQL code. Yo 'll learn hat the are and
ho to create them in this chapter. Yo 'll also learn hat e ceptions are, ho to create them, and ho
to handle them.
C 5: C , , PL/SQL.
PL/SQL allo s o to insert or pdate data sing SQL, and o 'll see e amples of ho to do that in this
chapter. Yo 'll also learn hat c rsors are, ho to se them, and hat arra s are.
C 6: R , , .
Using record t pes in PL/SQL can impro e o r code and o 'll learn hat the are and ho to se
them in this chapter. Yo 'll learn hat collections are, the different t pes of collections, and hat the
BULK COLLECT feat re is.
C 7: P
The final chapter ill e plain hat nested blocks are and ho to create them. Yo 'll also learn hat
packages are, the difference bet een the specification and the bod , h to se them, and ho to
create them.
● Oracle De G m: this ebsite contains man q i es for PL/SQL code hich can help impro e
o r kno ledge and let o practice PL/SQL.
● Ste e Fe erstein's PL/SQL blog: Ste e's blog contains a range of great posts and tips on
PL/SQL.
● StackO erflo q estions: Read some of the older q estions or tr to ans er some of the
ne er q estions on PL/SQL.
.Da aba eS a .c m
PL/SQL T ial
C 1: I Y F PL/SQL P
What Is PL/SQL?
PL/SQL stands for Proced ral Lang age/Str ct red Q er Lang age, and is an e pansion of the SQL
lang age de eloped b Oracle. It incl des a set of proced ral feat res (IF THEN ELSE logic, loops,
ariables) in addition to the SQL lang age. The code is ritten and e ec ted on an Oracle database.
The SQL lang age incl des man commands and feat res for reading and pdating data in o r
database, s ch as SELECT, INSERT, UPDATE, and DELETE. Man applications and ebsites are b ilt
sing SQL to interact ith a database. These applications can do all sorts of things s ch as:
What abo t all the b siness logic that is needed along ith this?
● Recording deleted records in a back p or a dit table rather than j st deleting them
This logic is often added into the application code: in PHP, C#, ASP, or man other lang ages.
B t o can also se PL/SQL for this logic. Yo 'll learn ho to do that in this t torial.
Wh Use PL/SQL?
Yo don't need to se PL/SQL to add b siness logic to o r applications, b t there are se eral reasons
o ma ant to.
.Da aba eS a .c m
PL/SQL T ial
I D S D
When o rite o r b siness logic and implementation details on the database, it's closel tied to the
database that ses it. Br n Lle ell n rites here:
"The implementation details are the tables and the SQL statements that manip late them. These are
hidden behind a PL/SQL interface. This is the Thick Database paradigm: select, insert, pdate, delete,
merge, commit, and rollback are iss ed onl from database PL/SQL. De elopers and end- sers of
applications b ilt this a are happ ith their correctness, maintainabilit , sec rit , and
performance."
I P
Storing o r b siness logic in PL/SQL code means that it ma perform better than application code
beca se PL/SQL is closel tied to SQL and the Oracle database. It all r ns on the same ser er, hich in
theor ill pro ide a performance impro ement.
C A M F -E
If o ha e o r b siness logic stored on the database, o can pro ide that to applications that se it.
Yo can ha e different applications se this database, and if the all se the same PL/SQL f nction
then the ill all manip late data in the same a .
There are se eral disad antages to sing PL/SQL, s ch as being harder to manage so rce control,
splitting logic bet een applications and databases making it harder to manage, and being tied to an
Oracle database. Ho e er I think these are minor disad antages, as so rce control ith PL/SQL code
is fairl good, and it's not er often that organisations change major database endors - and if the do,
code is likel to be re ritten an a .
Yo 're here to learn abo t PL/SQL, so no e kno hat it is and h o o ld ant to se it, let's
get started ith the code.
A piece of PL/SQL code is often called a program. A PL/SQL program is str ct red in blocks. It's a bit
different to ho f nctions inside a class ork.
● Declarati e section: this is here ariables are declared ( hich o 'll learn abo t later).
● E ec table section: this is the code that is r n as part of the program goes.
.Da aba eS a .c m
PL/SQL T ial
The onl req ired part of a PL/SQL program is the e ec table section. The other t o sections
(declarati e and e ception) are optional.
The e ec table part of a PL/SQL program starts ith the ke ord BEGIN and ends ith the ke ord
END. The are often ritten on separate lines, like this:
BEGIN
END;
The END ke ord ends ith a semicolon, b t the BEGIN ke ord doesn't need a semicolon.
The BEGIN ke ord starts the e ec table section of o r program. E er thing after the BEGIN
statement is e ec ted, ntil the END statement is reached.
This co ld be o r entire PL/SQL program. J st three lines like this. It on't do an thing, b t it ill r n.
● Are o reading this at ork, and ha e access to an Oracle database for de elopment or
testing? Use an IDE that o r compan or team has a ailable, s ch as SQL De eloper.
● Are o sing this at home? Install Oracle E press and SQL De eloper (both free) to be able to
r n code on o r o n comp ter.
In this t torial, e'll be sing Li eSQL as it's the easiest to get started on.
Open Li eSQL
.Da aba eS a .c m
PL/SQL T ial
2. Click on SQL Worksheet on the left. Yo 'll be taken to the Sign On page.
3. If o ha e an Oracle acco nt (it's free), enter o r sername and pass ord. If not, click Create
Acco nt.
.Da aba eS a .c m
PL/SQL T ial
The SQL Worksheet is then displa ed. This is here o can r n SQL statements and see o r o tp t.
If o ' e learned to program before, o 'll probabl remember riting o r first Hello World program.
Hello World is a term in programming here o learn ho to rite some te t to the comp ter screen
in a programming lang age. The te t is often called "Hello World" as a tradition.
So, e'll se PL/SQL code to rite the te t "Hello World" to the screen.
.Da aba eS a .c m
PL/SQL T ial
BEGIN
END;
Lea e a blank line bet een BEGIN and END. We'll p t some code inside there in the moment.
As mentioned before, e'll be sing Li eSQL for this t torial. If o 're sing an IDE s ch as SQL
De eloper, enter o r code there.
The PUT_LINE f nction is contained in a package called DBMS_OUTPUT. A package is like a librar in
other programming lang ages. It contains a set of related PL/SQL programs. We'll learn abo t
packages and ho to create them later in this t torial.
The te t e ant to displa is "Hello World". This is specified as a parameter, hich is inside the
brackets that appear after the PUT_LINE f nction.
So, pdate o r code so it r ns the DBMS_OUTPUT.PUT_LINE f nction in bet een the BEGIN and
END blocks, ith the parameter of "Hello World".
DBMS_OUTPUT.PUT_LINE('Hello World');
BEGIN
DBMS_OUTPUT.PUT_LINE('Hello World');
END;
The PUT_LINE f nction incl des the te t "Hello World" in single q otes, as that's the standard in SQL
for orking ith strings or te t al es. We also end the line ith a semicolon, so the database kno s
that e ha e reached the end of the line.
.Da aba eS a .c m
PL/SQL T ial
Click the R n b tton on the top right to r n the program. The code ill r n and displa the te t in the
o tp t section at the bottom of the screen:
In Li eSQL, it sho s one line sa ing "Statement processed", hich means the PL/SQL program has r n
s ccessf ll . The second line sa s "Hello World", hich is the te t inside o r code.
If o 're sing SQL De eloper, o can click the R n b tton to r n the PL/SQL code and o 'll see a
similar o tp t. If o don't see the o tp t, it's beca se the DBMS_OUTPUT is disabled b defa lt in
SQL De eloper. I' e ritten a post ith steps and screenshots on ho to enable it here. (TODO add
link in ne tab)
Q i
Q estion 1:
.Da aba eS a .c m
PL/SQL T ial
Q estion 2:
● START
● RUN
● BEGIN
● END
Q estion 3:
What is the b ilt-in f nction sed for displa ing o tp t to the screen?
● PRINTLN
● WRITE
● SAVE
● PUT_LINE
Q estion 4:
BEGIN
DBMS_OUTPUT.PUT_LINE
END;
.Da aba eS a .c m
PL/SQL T ial
● Diffe en da a e of he e a iable
O P e io Code
BEGIN
DBMS_OUTPUT.PUT_LINE('Hello World');
END;
Wha if o an ed o change ha e ?
BEGIN
DBMS_OUTPUT.PUT_LINE('I am learning');
END;
Statement processed.
I am learning
.Da aba eS a .c m
PL/SQL T ial
DECLARE
BEGIN
DBMS_OUTPUT.PUT_LINE('I am learning');
END;
Le ' decla e o fi a iable. We'll call i "l_ e ". The lo e ca e L i ed a a efi o indica e i ' a
local a iable ( hich mean i ' onl ele an fo he og am e a e nning). I ' no a e i emen o
add hi efi , b i ' ecommended b man de elo e incl ding S e en Fe e ein.
DECLARE
l_text
BEGIN
DBMS_OUTPUT.PUT_LINE('I am learning');
END;
DECLARE
l_text VARCHAR2(50)
BEGIN
DBMS_OUTPUT.PUT_LINE('I am learning');
END;
.Da aba eS a .c m
PL/SQL T ial
DECLARE
BEGIN
DBMS_OUTPUT.PUT_LINE('I am learning');
END;
Statement processed.
I am learning
Le ' change ha no . Remo e he e "I am lea ning", and he ingle o e , and he a iable
name l_ e in he e in ead:
DECLARE
BEGIN
DBMS_OUTPUT.PUT_LINE(l_text);
END;
No , n hi code:
Statement processed.
Hello World
.Da aba eS a .c m
PL/SQL T ial
Inden ing
A e add mo e and mo e code o o PL/SQL og am, i can ge ha de o ead. Li eSQL and man
IDE highligh he ke o d and e al e in diffe en colo , b he e' mo e e can do o
im o e eadabili .
T adi ionall , DECLARE, BEGIN, and END ke o d a e all aligned o he lef and no inden ed. Code
in each of ho e ec ion i inden ed. Yo can do hi no i h o code:
DECLARE
BEGIN
DBMS_OUTPUT.PUT_LINE(l_text);
END;
DECLARE
l_text VARCHAR2(50);
BEGIN
DBMS_OUTPUT.PUT_LINE(l_text);
END;
Statement processed.
.Da aba eS a .c m
PL/SQL T ial
We need o e he a iable o ome hing in ide o og am. We can do hi b ecif ing he a iable
name, hen he colon and e al ign, hen he a iable. Thi need o be done in ide he BEGIN
ec ion of he code:
DECLARE
l_text VARCHAR2(50);
BEGIN
DBMS_OUTPUT.PUT_LINE(l_text);
END;
Statement processed.
Hello World
DECLARE
l_text VARCHAR2(50);
BEGIN
DBMS_OUTPUT.PUT_LINE(l_text);
END;
Statement processed.
Hello World
So, hen o decla e a iable , o can ei he a ign hem a he ime o decla e hem, o a ign
hem la e .
N mbe Da a T e
.Da aba eS a .c m
PL/SQL T ial
DECLARE
l_mynumber NUMBER(8);
BEGIN
l_mynumber := 12;
DBMS_OUTPUT.PUT_LINE(l_mynumber);
END;
If e n hi code, e ge hi o :
Statement processed.
12
DECLARE
l_mynumber NUMBER(8);
BEGIN
l_mynumber := 491;
DBMS_OUTPUT.PUT_LINE(l_mynumber);
END;
Statement processed.
491
.Da aba eS a .c m
PL/SQL T ial
In PL/SQL, conca ena ion i done i h a do ble i e cha ac e . Yo ecif a al e, hen a do ble
i e, hen ano he al e, and he o al e a e hen ea ed a one. Thi i hel f l in man i a ion ,
one of hem being he PUT_LINE f nc ion.
DECLARE
l_mynumber NUMBER(8);
BEGIN
l_mynumber := 491;
END;
R nning hi code gi e hi e l:
Statement processed.
One hing o kee in mind i h conca ena ion i ace . I' e added a ace af e he o d " a " in he
e al e. Wi ho he ace, he n mbe ill be laced igh ne o he o d " a ", beca e
conca ena ion doe no a oma icall add ace :
DECLARE
l_mynumber NUMBER(8);
BEGIN
l_mynumber := 491;
END;
Statement processed.
Conca ena ion i e hel f l hen i come o o king i h a iable and con c ing hel f l
o , a e' e een abo e.
Adding N mbe
.Da aba eS a .c m
PL/SQL T ial
Yo can add n mbe oge he in PL/SQL. Thi i done ing he + mbol be een o n mbe , j
like o he og amming lang age and in SQL.
DECLARE
l_mynumber NUMBER(8);
BEGIN
l_mynumber := 4 + 9;
END;
Statement processed.
S b ac ing N mbe
DECLARE
l_mynumber NUMBER(8);
BEGIN
l_mynumber := 100 - 5;
END;
Statement processed.
M l i l ing N mbe
.Da aba eS a .c m
PL/SQL T ial
DECLARE
l_mynumber NUMBER(8);
BEGIN
l_mynumber := 20 * 4;
END;
Statement processed.
Di iding N mbe
Finall , PL/SQL allo o o di ide n mbe b ing he / cha ac e . The follo ing code ill di ide
100 b 4 and di la he e l .
DECLARE
l_mynumber NUMBER(8);
BEGIN
l_mynumber := 100 / 4;
END;
Statement processed.
If he n mbe doe no di ide e enl , he al e ill ill be calc la ed and di la ed, b ma no look
nea .
DECLARE
l_mynumber NUMBER(8,2)
BEGIN
l_mynumber := 100 / 7;
.Da aba eS a .c m
PL/SQL T ial
END;
Statement processed.
Con an
In he code o fa , e' e decla ed a iable and a igned hem. We' e al o decla ed a iable and
a igned hem la e in he PL/SQL og am. Thi i an ad an age of ing a iable - o can da e
he al e of hem in o og am.
Fo e am le, le ' a o had hi PL/SQL og am hich calc la ed he ci c mfe ence of a ci cle. The
ci c mfe ence of a ci cle i 2 , o 2 ime he adi ime i. The al e of i i a o ima el e al o
3.14159.
DECLARE
BEGIN
l_radius := 8;
END;
O o look like hi :
Statement processed.
DECLARE
.Da aba eS a .c m
PL/SQL T ial
BEGIN
l_radius := 8;
END;
O o look like hi :
Statement processed.
So, le ' mo e ha n mbe in o a a iable. We'll e i hen e decla e i beca e e don' need o
change i .
DECLARE
BEGIN
l_radius := 8;
END;
The o of hi code i :
Statement processed.
DECLARE
BEGIN
.Da aba eS a .c m
PL/SQL T ial
l_radius := 8;
l_pi := 4;
END;
Statement processed.
The circumference is 64
DECLARE
BEGIN
l_radius := 8;
END;
Statement processed.
DECLARE
.Da aba eS a .c m
PL/SQL T ial
BEGIN
l_radius := 8;
L_pi := 4;
END;
Thi e o mean o can' a ign a al e o hi a iable, beca e o ' e decla ed i a a con an . Thi
i ha e e ec ed.
Concl ion
● Ho o decla e con an
Well done fo ge ing hi fa ! In he ne cha e , o 'll lea n abo ome ke fea e of PL/SQL:
condi ional logic and loo .
Q i
Q e ion 1:
● START
● BEGIN
.Da aba eS a .c m
PL/SQL T ial
● DECLARE
● VARIABLE
Q e ion 2:
Q e ion 3:
Wha i a con an ?
● A f nc ion ha di la da a o he c een.
Q e ion 4:
DECLARE
l_radius NUMBER(8);
BEGIN
END;
.Da aba eS a .c m
PL/SQL T ial
● Loop
Each of he e can be done b ing PL/SQL ke o d ha allo condi ion . Condi ion a e he e o
n diffe en line of code ba ed on a pecific condi ion. Yo can pecif he condi ion o check, and
hi check ill e n e o fal e. If i ' e, hen a e of code i n.
A Simple IF S a emen
IF (condition) THEN
our_code;
END IF;
Thi look imila in man p og amming lang age , and he onl diffe ence a e all he ke o d
and mbol ed.
DECLARE
.Da aba eS a .c m
PL/SQL T ial
BEGIN
DBMS_OUTPUT.PUT_LINE('This is a square.');
END IF;
END;
The IF a emen end i h he END IF. We hen fini h he code i h he END a emen . Al o no ice
he line ha ha e a emicolon: he p _line f nc ion, he END IF, and he END a emen .
If e n hi code, hi i o p :
Statement processed.
This is a square.
DECLARE
BEGIN
DBMS_OUTPUT.PUT_LINE('This is a square.');
END IF;
END;
Statement processed.
.Da aba eS a .c m
PL/SQL T ial
We can do ha ing he ELSE a emen . The ELSE a emen n code if he condi ion i fal e. In a
diag am, i look like hi .
IF (condition) THEN
our_code;
ELSE
our_other_code;
END IF;
DECLARE
BEGIN
DBMS_OUTPUT.PUT_LINE('This is a square.');
ELSE
DBMS_OUTPUT.PUT_LINE('This is a rectangle.');
END IF;
END;
The onl change o hi code a e adding he ELSE a emen and a p _line f nc ion o a "Thi i a
ec angle".
The o p of hi code i :
Statement processed.
This is a square.
.Da aba eS a .c m
PL/SQL T ial
Thi o p i ill ho ing he me age of " q a e" beca e bo h he leng h and id h a iable a e
he ame. We can change one and he o p ill change.
DECLARE
BEGIN
DBMS_OUTPUT.PUT_LINE('This is a square.');
ELSE
DBMS_OUTPUT.PUT_LINE('This is a rectangle.');
END IF;
END;
Statement processed.
This is a rectangle.
The code ha de e mined ha he leng h and id h (17 and 20) a e diffe en , o i ha n he code
af e he ELSE a emen and no he IF a emen .
So ha ' ho o can pe fo m a imple IF a emen and n code if he condi ion i e and diffe en
code if he condi ion i fal e.
Ano he fea e of PL/SQL IF a emen i he abili o ha e m l iple condi ion in ide a ingle IF
a emen .
U ing o ea lie e ample, e check if he leng h and id h a e he ame, di pla " q a e" if he a e
and " ec angle" if he a e no . Wha if e an o add ano he check o ee if he id h i le han 0?
O code o fa ha n' incl ded an logic fo hi . If bo h n mbe a e nega i e, hen he code ill ill
n:
DECLARE
BEGIN
.Da aba eS a .c m
PL/SQL T ial
DBMS_OUTPUT.PUT_LINE('This is a square.');
ELSE
DBMS_OUTPUT.PUT_LINE('This is a rectangle.');
END IF;
END;
Statement processed.
This is a rectangle.
IF (condition) THEN
our_code;
our_second_code
ELSE
our_other_code;
END IF;
DECLARE
BEGIN
DBMS_OUTPUT.PUT_LINE('This is a square.');
ELSE
DBMS_OUTPUT.PUT_LINE('This is a rectangle.');
.Da aba eS a .c m
PL/SQL T ial
END IF;
END;
The o p i :
Statement processed.
Wha if bo h he id h and leng h a e nega i e? Which condi ion ill be checked? The a e eq al and
nega i e o he mee bo h condi ion . Le ' e hi o .
DECLARE
BEGIN
DBMS_OUTPUT.PUT_LINE('This is a square.');
ELSE
DBMS_OUTPUT.PUT_LINE('This is a rectangle.');
END IF;
END;
Statement processed.
This is a square.
DECLARE
.Da aba eS a .c m
PL/SQL T ial
BEGIN
DBMS_OUTPUT.PUT_LINE('This is a square.');
ELSE
DBMS_OUTPUT.PUT_LINE('This is a rectangle.');
END IF;
END;
The check fo he id h being nega i e come fi , and hen if ha i fal e, he leng h and id h a e
checked o ee if he a e eq al.
Statement processed.
DECLARE
l_width NUMBER(5) := 6;
BEGIN
DBMS_OUTPUT.PUT_LINE('This is a square.');
ELSE
DBMS_OUTPUT.PUT_LINE('This is a rectangle.');
.Da aba eS a .c m
PL/SQL T ial
END IF;
END;
Statement processed.
This is a rectangle.
Ra he han adding ano he IF condi ion, e can adj he one e al ead ha e. PL/SQL allo o o
add m l iple c i e ia in ide an IF a emen condi ion.
DECLARE
l_width NUMBER(5) := 6;
BEGIN
DBMS_OUTPUT.PUT_LINE('This is a square.');
ELSE
DBMS_OUTPUT.PUT_LINE('This is a rectangle.');
END IF;
END;
Statement processed.
.Da aba eS a .c m
PL/SQL T ial
DECLARE
BEGIN
DBMS_OUTPUT.PUT_LINE('This is a square.');
ELSE
DBMS_OUTPUT.PUT_LINE('This is a rectangle.');
END IF;
END;
The code ho hi o p :
Statement processed.
So fa e' e looked a code ha check ha condi ion a e e. Wha if e an o check if condi ion
a e fal e?
Gene all , i ' be e p ac ice o check if condi ion a e e, and i make fo ea ie eading of code.
Ho e e , ome ime o ma need o check if ome hing i fal e. Thi can be done i h he NOT
ke o d.
Le ' ake o ea lie e ample and change he condi ion f om checking if he id h and leng h a e le
han e o o checking if he id h and leng h a e no g ea e han e o
DECLARE
.Da aba eS a .c m
PL/SQL T ial
BEGIN
DBMS_OUTPUT.PUT_LINE('This is a square.');
ELSE
DBMS_OUTPUT.PUT_LINE('This is a rectangle.');
END IF;
END;
We ha e added he o d NOT o ide he b acke , hich mean he condi ion in ide he b acke
need o be fal e fo he IF a emen o be e. The NOT ke o d ha e e ed he logic.
We co ld ha e lef i like hi :
.Da aba eS a .c m
PL/SQL T ial
Ne ed IF S a emen
We' e j een ho o can e IF a emen in PL/SQL. Thi allo o o check condi ion and n
diffe en code depending on he e condi ion .
IF (condition) THEN
IF (condition) THEN
our_code;
ELSE
more_code;
END IF;
our_second_code
ELSE
our_other_code;
END IF;
Yo add in ano he IF a emen he e o code o ld no mall go. Yo can e ELSE and ELSIF
a emen he e a ell.
DECLARE
BEGIN
END IF;
.Da aba eS a .c m
PL/SQL T ial
END IF;
DBMS_OUTPUT.PUT_LINE('This is a square.');
ELSE
DBMS_OUTPUT.PUT_LINE('This is a rectangle.');
END IF;
END;
Statement processed.
A CASE a emen le o pecif one o mo e condi ion , and if he condi ion i e, hen ome code
i n. I ' ea ie o i e and ead han a long IF a emen .
CASE condition
.Da aba eS a .c m
PL/SQL T ial
ELSE default_code;
END CASE;
DECLARE
l_width NUMBER(5) := 5;
BEGIN
CASE l_length
WHEN 10 THEN
WHEN 20 THEN
WHEN 30 THEN
ELSE
END CASE;
END;
Thi code ill check he l_leng h al e, and di pla a pecific o p if i i eq al o 10, 20, o 30. If i '
diffe en , i di pla a diffe en me age.
If e n he code, hi i ha e ee:
Statement processed.
.Da aba eS a .c m
PL/SQL T ial
Statement processed.
DECLARE
l_width NUMBER(5) := 5;
BEGIN
CASE l_length
WHEN 10 THEN
WHEN 20 THEN
WHEN 30 THEN
ELSE
END CASE;
END;
Statement processed.
Onl one of he condi ion in he CASE a emen i calc la ed. Unlike o he p og amming lang age ,
e don' need o add a b eak a emen o e i hi code. A oon a he fi c i e ia i me , i e i he
ca e a emen . If no ma che a e fo nd, he ELSE a emen i n.
Wha i a Loop?
We' e j lea ned abo IF a emen and CASE a emen , hich le o n diffe en piece of
code depending on diffe en condi ion .
.Da aba eS a .c m
PL/SQL T ial
Wha i a loop?
A loop i a fea e of p og amming lang age ha le o n he ame piece of code m l iple ime .
Yo can pecif he condi ion ha en e he loop i n, ch a he ma im m n mbe of i e a ion
of he loop, o n il a ce ain condi ion i me .
A Ba ic Loop
The mo ba ic kind of loop in PL/SQL ill a a loop (a e of code ha i e ec ed m l iple ime ). I
ill onl e i hen o ell i o. I e he follo ing ke o d :
● LOOP o a he loop
BEGIN
LOOP
our_code
IF (condition) THEN
EXIT;
END IF;
END LOOP;
END;
The LOOP and END LOOP indica e ha all code in ide i ho ld be n m l iple ime . The code in ide
he loop i e ec ed, line b line. When he END LOOP i eached, he code a again f om he
LOOP a emen .
BEGIN
LOOP
END LOOP;
END;
.Da aba eS a .c m
PL/SQL T ial
Thi i called an infini e loop. I happen beca e he code i looping and o ha en' old i o op.
Thi i an i e ha happen occa ionall in code, and i ome hing o be a oided.
BEGIN
LOOP
IF (condition) THEN
EXIT;
END IF;
END LOOP;
END;
DECLARE
l_loop_counter NUMBER(3) := 0;
BEGIN
LOOP
IF (condition) THEN
EXIT;
END IF;
END LOOP;
END;
DECLARE
l_loop_counter NUMBER(3) := 0;
.Da aba eS a .c m
PL/SQL T ial
BEGIN
LOOP
l_loop_counter := l_loop_counter + 1;
IF (condition) THEN
EXIT;
END IF;
END LOOP;
END;
Thi code ill inc ea e ha a iable b 1 each ime he loop i n. We hen need o add hi o o
condi ion, o he loop e i hen e an i o.
DECLARE
l_loop_counter NUMBER(3) := 0;
BEGIN
LOOP
l_loop_counter := l_loop_counter + 1;
IF (l_loop_counter = 5) THEN
EXIT;
END IF;
END LOOP;
END;
Statement processed.
A message here.
A message here.
A message here.
A message here.
A message here.
The o p ho he line "A me age he e" fi e ime , hich mee he c i e ia of o code. The loop
co n e a a 0, i inc emen ed b 1 each ime i i n, and once i ge o 5 he loop e i .
.Da aba eS a .c m
PL/SQL T ial
Statement processed.
A message here.
A message here.
A message here.
A message here.
A message here.
A message here.
A message here.
A message here.
A message here.
A message here.
DECLARE
l_loop_counter NUMBER(3) := 0;
BEGIN
LOOP
l_loop_counter := l_loop_counter + 1;
IF (l_loop_counter = 5) THEN
EXIT;
END IF;
END LOOP;
END;
Statement processed.
A message here: 1
A message here: 2
A message here: 3
.Da aba eS a .c m
PL/SQL T ial
A message here: 4
A message here: 5
The Fo Loop
PL/SQL offe ano he pe of loop called he FOR loop. Thi FOR loop allo o o define he c i e ia
of he loop a he a , hich make i ea ie o ee ho he loop n and ea ie o a oid "infini e
loop" i e .
our_code
END LOOP;
DECLARE
l_loop_counter NUMBER(3);
BEGIN
END LOOP;
END;
.Da aba eS a .c m
PL/SQL T ial
1 .. 5
I ' a n mbe , hen a pace, hen o pe iod , hen a pace, hen ano he n mbe . If i ' no i en in
hi a , o 'll ge a n a e o . I' e done hi man ime - fo go en he pace, onl p in one
pe iod - and onde ed h he code didn' n. So make e o check ha hen o ie o
code.
If e n hi code, e ge hi e l:
Statement processed.
Loop number: 1
Loop number: 2
Loop number: 3
Loop number: 4
Loop number: 5
DECLARE
l_loop_counter NUMBER(3);
BEGIN
END LOOP;
END;
Statement processed.
Loop number: 12
Loop number: 13
Loop number: 14
Loop number: 15
Loop number: 16
Loop number: 17
Loop number: 18
.Da aba eS a .c m
PL/SQL T ial
Loop number: 19
Loop number: 20
our_code
END LOOP;
Thi loop n a incl de a condi ion, hich mean he code in ide he loop onl n if he condi ion i
e. The code in ide he loop m en e ha he condi ion e en all e l in FALSE, o he i e
o 'll end p i h an infini e loop.
DECLARE
l_loop_counter NUMBER(3);
BEGIN
END LOOP;
END;
DECLARE
l_loop_counter NUMBER(3) := 0;
BEGIN
l_loop_counter := l_loop_counter + 1;
.Da aba eS a .c m
PL/SQL T ial
END LOOP;
END;
Statement processed.
Loop number: 0
Loop number: 1
Loop number: 2
Loop number: 3
Loop number: 4
A o can ee, he e a e h ee diffe en pe of loop in PL/SQL. The e a e ome ligh diffe ence
be een each of hem ho gh, hich a e mma i ed in hi able:
Incl de he e i c i e ia No Ye Ye
Inc emen a co n e No Ye No
R n he fi line of he loop Ye Ye No al a
One of he main diffe ence be een he WHILE and FOR loop i ha he WHILE loop ma no
al a n he code in ide he loop. If he condi ion ed in he WHILE loop i fal e hen i i fi
checked, he code in ide he loop i no n.
Concl ion
The PL/SQL lang age incl de po e f l fea e fo nning ce ain piece of code in ce ain
condi ion . Thi incl de IF THEN ELSE logic, CASE a emen , and looping. The e a e h ee pe of
loop (Ba ic, FOR, and WHILE), each of hem a e ligh l diffe en .
Q i
Q e ion 1:
.Da aba eS a .c m
PL/SQL T ial
● ELSE
● OTHERWISE
● FINAL
● END
Q e ion 2:
● Se p he da a eq i ed o end an email
Q e ion 3:
Q e ion 4:
DECLARE
l_loop_counter NUMBER(3) := 8;
BEGIN
l_loop_counter := l_loop_counter + 1;
END LOOP;
.Da aba eS a .c m
PL/SQL T ial
END;
● I ill nb no o p i ho n.
.Da aba eS a .c m
PL/SQL T ial
● Wha ced e a d f ci a e
● H c ea e a ced e
● H c ea e a f ci
● Wha a e ce i i a dh ha dle e
Le ' ge a ed!
Wh c ea e ed ced e ?
● I all f he c de be e ed b calli g i f m he c de
Wha i a PL/SQL F ci ?
.Da aba eS a .c m
PL/SQL T ial
● Pe f mi g calc la i a d e i g a al e? U e a f ci .
H C ea e a PL/SQL P ced e
IS AS
BEGIN
ced e_b d
The e a e a fe hi g ice he e:
O e m e a ame e ca be ided:
Af e defi e he a ame e :
.Da aba eS a .c m
PL/SQL T ial
E am le PL/SQL P ced e
DECLARE
l_ id h NUMBER(5) := 18;
BEGIN
DBMS_OUTPUT.PUT_LINE('Thi i a a e.');
ELSE
DBMS_OUTPUT.PUT_LINE('Thi i a ec a gle.');
END IF;
END;
● The ma im m le g h i 30 cha ac e
● The fi cha ac e m be a le e
● check_ ec a gle
● CHECK_RECTANGLE
● Check_Rec a gle
.Da aba eS a .c m
PL/SQL T ial
AS
AS
DECLARE
l_ id h NUMBER(5) := 18;
BEGIN
DBMS_OUTPUT.PUT_LINE('Thi i a a e.');
ELSE
DBMS_OUTPUT.PUT_LINE('Thi i a ec a gle.');
END IF;
If e hi c de, e ge a e me age:
.Da aba eS a .c m
PL/SQL T ial
AS
l_ id h NUMBER(5) := 18;
BEGIN
DBMS_OUTPUT.PUT_LINE('Thi i a a e.');
ELSE
DBMS_OUTPUT.PUT_LINE('Thi i a ec a gle.');
END IF;
Y 'll ge hi :
P ced e c ea ed.
Y c de a d ill l k like hi :
.Da aba eS a .c m
PL/SQL T ial
S a eme ce ed.
Thi i a ec a gle.
Y ca e EXEC:
S a eme ce ed.
Thi i a ec a gle.
BEGIN
check_ ec a gle;
END;
S a eme ce ed.
Thi i a ec a gle.
We ha e j c ea ed a ced e ha check al e a d de e mi e if a ha e i a a e
ec a gle.
O e a c ld d i i :
● Fi d he c de ed c ea e he ced e
● M dif he a iable
● Rec ea e he ced e
● Call he ced e
.Da aba eS a .c m
PL/SQL T ial
O c de l k like hi fa :
AS
l_ id h NUMBER(5) := 18;
BEGIN
DBMS_OUTPUT.PUT_LINE('Thi i a a e.');
ELSE
DBMS_OUTPUT.PUT_LINE('Thi i a ec a gle.');
END IF;
AS
l_ id h NUMBER(5) := 18;
BEGIN
DBMS_OUTPUT.PUT_LINE('Thi i a a e.');
ELSE
DBMS_OUTPUT.PUT_LINE('Thi i a ec a gle.');
.Da aba eS a .c m
PL/SQL T ial
END IF;
AS
l_ id h NUMBER(5) := 18;
BEGIN
DBMS_OUTPUT.PUT_LINE('Thi i a a e.');
ELSE
DBMS_OUTPUT.PUT_LINE('Thi i a ec a gle.');
END IF;
AS
BEGIN
.Da aba eS a .c m
PL/SQL T ial
DBMS_OUTPUT.PUT_LINE('Thi i a a e.');
ELSE
DBMS_OUTPUT.PUT_LINE('Thi i a ec a gle.');
END IF;
Le ' hi he da aba e.
P ced e c ea ed.
The f m hi a eme i :
S a eme ce ed.
Thi i a ec a gle.
Thi h he f ll i g :
S a eme ce ed.
Thi i a ec a gle.
.Da aba eS a .c m
PL/SQL T ial
The f hi i :
S a eme ce ed.
Thi i a ec a gle.
S a eme ce ed.
Thi i a ec a gle.
S a eme ce ed.
Thi i a big a e.
S a eme ce ed.
The id h le g h i ega i e.
He e' ced e a he m me :
AS
BEGIN
.Da aba eS a .c m
PL/SQL T ial
DBMS_OUTPUT.PUT_LINE('Thi i a a e.');
ELSE
DBMS_OUTPUT.PUT_LINE('Thi i a ec a gle.');
END IF;
AS
BEGIN
DBMS_OUTPUT.PUT_LINE('Thi i a a e.');
ELSE
DBMS_OUTPUT.PUT_LINE('Thi i a ec a gle.');
END IF;
AS
BEGIN
.Da aba eS a .c m
PL/SQL T ial
ELSE
END IF;
If e hi c de, hi i he e ge :
P ced e c ea ed.
DECLARE
BEGIN
END;
R i g hi c de h hi :
S a eme ce ed.
Thi i a ec a gle.
me age_ al VARCHAR2(100)
);
DECLARE
.Da aba eS a .c m
PL/SQL T ial
BEGIN
INSERT INTO me age_ (me age_ al) VALUES (l_ _me age);
END;
1 ( ) i e ed.
If e SELECT f m he able, e ca ee al e.
MESSAGE_VAL
Thi i a ec a gle.
H C ea e a PL/SQL F ci
C ea i g a f ci i imila c ea i g a ced e:
RETURN e _da a e
IS AS
BEGIN
f c i _b d
END f c i _ ame;
The e a e a fe hi g ice he e:
.Da aba eS a .c m
PL/SQL T ial
O e m e a ame e ca be ided:
Af e defi e he a ame e :
● S ecif ei he IS AS a he f ci c de.
E am le PL/SQL F ci
O f ci ill l k like hi :
RETURN NUMBER
AS
BEGIN
END;
B he f ci d e ' d a hi g.
Le ' ie me f ci c de.
.Da aba eS a .c m
PL/SQL T ial
RETURN NUMBER
AS
BEGIN
RETURN l_ id h * l_le g h;
END;
Le ' c ea e hi f ci . The h :
F c i c ea ed.
BEGIN
END;
Thi c de h he f ll i g :
S a eme ce ed.
20
FROM d al;
SHAPE_AREA(5,4)
20
E ce i i PL/SQL
Wha i a e ce i i PL/SQL?
A e ce i i a e ha ha e he i g c de. S me e i c de ca be f d
bef e he c de, ch a mi i g emic l he cha ac e . H e e , e ce i cc
he c de a d ca ' be edic ed bef e i g he c de, ch a addi g a e al e
a mbe da a e.
.Da aba eS a .c m
PL/SQL T ial
S a f E ce i Ha dli g i PL/SQL
BEGIN
e ec able_c de;
EXCEPTION
WHEN e ce i _ e THEN
e ce i _c de;
e ce i _c de;
END;
E am le E ce i C de i PL/SQL
The c de l k like hi :
DECLARE
.Da aba eS a .c m
PL/SQL T ial
l_le g h NUMBER := 4;
l_ id h NUMBER := 5;
l_a ea NUMBER(3);
BEGIN
l_a ea := l_le g h * l_ id h;
END;
O l_a ea a iable ha a ma im m i e f 3. We ca hi c de a d ge hi :
S a eme ce ed.
The a ea i : 20
Le ' a e ha e a le g h a d id h ha a e b h h ee digi .
DECLARE
l_ id h NUMBER := 500;
l_a ea NUMBER(3);
BEGIN
l_a ea := l_le g h * l_ id h;
END;
Wha ha e he e he c de?
We ge a e me age:
Thi e me age ha a c de: ORA-06502. The me age a he mbe eci i i la ge. Thi
i beca e 400 * 500 i 200,000, hich i la ge f he NUMBER(3) a iable.
Ra he ha di la hi e me age, e ca ie me c de ha ell he g am ha d . We
d hi i g he EXCEPTION ec i .
DECLARE
l_ id h NUMBER := 500;
.Da aba eS a .c m
PL/SQL T ial
l_a ea NUMBER(3);
BEGIN
l_a ea := l_le g h * l_ id h;
EXCEPTION
END;
If e hi c de, e ge hi :
S a eme ce ed.
Rai i g E ce i i PL/SQL
O e e am le f hi i ha if e f he a ame e i ega i e?
O c de c ld l k like hi :
DECLARE
l_ id h NUMBER := 3;
.Da aba eS a .c m
PL/SQL T ial
l_a ea NUMBER(3);
BEGIN
l_a ea := l_le g h * l_ id h;
EXCEPTION
END;
The i :
S a eme ce ed.
The a ea i : -12
We ca a id hi b c ea i g ai i g e ce i .T d hi :
● Check he c i e ia ha ca e hi i e, a d ai e he e ce i if he a e e
DECLARE
l_ id h NUMBER := 3;
l_a ea NUMBER(3);
BEGIN
l_a ea := l_le g h * l_ id h;
EXCEPTION
END;
.Da aba eS a .c m
PL/SQL T ial
DECLARE
l_ id h NUMBER := 3;
l_a ea NUMBER(3);
BEGIN
l_a ea := l_le g h * l_ id h;
END IF;
EXCEPTION
END;
O e c de ill l k like hi :
DECLARE
l_ id h NUMBER := 3;
l_a ea NUMBER(3);
BEGIN
l_a ea := l_le g h * l_ id h;
.Da aba eS a .c m
PL/SQL T ial
END IF;
EXCEPTION
END;
We ca hi c de.
S a eme ce ed.
C cl i
E ce i a ee ha a e e c e ed a g am i i g. The ca be ha dled i hi
PL/SQL c de, he i e he ill di la a e i IDE i a lica i .
Q i
Q e i 1
● The a e b h he ame.
● P ced e ca be ed i eg la SQL, b f ci ca .
.Da aba eS a .c m
PL/SQL T ial
Q e i 2
● N hi g, hi ke di alid.
● I de e mi e if c de ill i e e da a i a able da e e i i g da a.
Q e i 3
Wha i a e ce i ?
● A e ha ha e he c ea e ced e f ci , ch a a mi i g b acke .
● The a f a IF a eme ha if c i e ia a e me .
● A e ha ha e hile c de i i g.
● A c llec i f da a ha i i e ed i a able.
Q e i 4
H ca he c de i a ced e?
● Y ca ' ced e , ca l f ci .
.Da aba eS a .c m
PL/SQL T ial
Cha e 5: C ,A a ,a dB C ec
In his chap er, e'll learn abo some pre sef l concep s in PL/SQL:
Wha a c rsor is
Inser ing, pda ing, and dele ing da a in ables sing PL/SQL
A c rsor is an area in memor ha Oracle crea es hen an SQL s a emen is r n. The c rsor con ains
se eral pieces of informa ion incl ding he ro s ha he s a emen has re rned (if i 's a SELECT
s a emen ), and a rib es abo he res l se s ch as he n mber of ro s impac ed b he s a emen .
There are o pes of c rsors in in Oracle SQL: implici c rsors and e plici c rsors.
Implici C rsors
An implici c rsor is a pe of c rsor a oma icall crea ed b Oracle hen an SQL s a emen is r n.
I 's called an implici c rsor beca se i 's crea ed a oma icall - o don' need o do an hing for i o
ge crea ed.
Ho can implici c rsors help s? For INSERT, UPDATE, and DELETE s a emen s, e can see se eral
a rib es of he s a emen s o nders and if he ha e orked or no .
.Da aba eS a .c m
PL/SQL T ial
fname VARCHAR2(50)
);
BEGIN
VALUES ('John');
END;
This code incl des he erm sql%ro co n . The "sql" is he objec name of he SQL s a emen ha ran
las . The "ro co n " is he a rib e of his mos recen SQL s a emen , and con ains he n mber of
ro s impac ed b he s a emen . The % sign indica es ha he ro co n is an a rib e of he sql
objec . So, sql%ro co n ill con ain he n mber of ro s impac ed b he mos recen SQL s a emen .
DECLARE
l_ o al_ro s NUMBER(10);
BEGIN
VALUES ('John');
l_ o al_ro s := sql%ro co n ;
END;
Yo can also se his informa ion in an IF s a emen and r n differen code based on he al e.
DECLARE
l_ o al_ro s NUMBER(10);
BEGIN
.Da aba eS a .c m
PL/SQL T ial
VALUES ('John');
l_ o al_ro s := sql%ro co n ;
ELSE
END IF;
END;
FNAME
John
We can make se of implici c rsors in PL/SQL i h UPDATE s a emen s. For e ample, his code
sho s s he n mber of ro s impac ed b he UPDATE s a emen .
BEGIN
UPDATE person
END;
FNAME
S san
.Da aba eS a .c m
PL/SQL T ial
Ano her a of checking for ro s being pda ed is o se he %FOUND and %NOTFOUND a rib es,
ra her han %ROWCOUNT.
BEGIN
UPDATE person
ELSE
END IF;
END;
This o p is sho n:
Ro s no pda ed.
The o p message sa s no ro s are pda ed. This is beca se he WHERE cla se doesn' ma ch an
of he e is ing ro s.
BEGIN
UPDATE person
SET fname='Mark'
.Da aba eS a .c m
PL/SQL T ial
ELSE
END IF;
END;
Ro s pda ed: 1
The same concep of an implici c rsor applies o a DELETE s a emen . We can ri e some code ha
dele es a ro and hen displa s an o p depending on if a ro as dele ed or no .
BEGIN
ELSE
END IF;
END;
Ro s no pda ed.
BEGIN
.Da aba eS a .c m
PL/SQL T ial
ELSE
END IF;
END;
Ro s pda ed: 1.
Firs , e declare a ariable o hold o r da a. Then, e selec a col mn al e from he able and s ore i
in his ariable. In his e ample, e'll j s selec a single al e, as e need o rea m l iple ro s
differen l .
DECLARE
l_fname VARCHAR2(50);
BEGIN
SELECT fname
INTO l_fname
FROM person;
END;
Firs , e' e declared a ariable called l_fname. Then in he BEGIN sec ion, e ha e selec ed he fname
col mn from he person able in o he l_fname ariable. This ariable no holds he al e from ha
q er . We hen o p i sing he PUT_LINE f nc ion.
.Da aba eS a .c m
PL/SQL T ial
S a emen processed.
Wha if here are o or more al es in he able? Ho do e handle his? O r ariable can onl hold
one al e.
FNAME
John
S san
DECLARE
l_fname VARCHAR2(50);
BEGIN
SELECT fname
INTO l_fname
FROM person;
END;
This error happens beca se e ha e o al es re rned from o r q er (John and S san), b onl
one ariable o s ore hem.
E plici C rsors
.Da aba eS a .c m
PL/SQL T ial
In Oracle PL/SQL, an e plici c rsor is one ha is declared b he PL/SQL code. Yo ha e more con rol
o er i and ho he da a is handled.
To declare a c rsor, o add a line in o he DECLARE sec ion of o r code. I incl des o r SELECT
s a emen .
DECLARE
CURSOR c_person IS
BEGIN
END;
DECLARE
CURSOR c_person IS
BEGIN
OPEN c_person;
END;
DECLARE
l_fname VARCHAR2(50);
CURSOR c_person IS
.Da aba eS a .c m
PL/SQL T ial
BEGIN
OPEN c_person;
END;
DECLARE
l_fname VARCHAR2(50);
CURSOR c_person IS
BEGIN
OPEN c_person;
CLOSE c_person;
END;
DECLARE
l_fname VARCHAR2(50);
CURSOR c_person IS
BEGIN
OPEN c_person;
CLOSE c_person;
END;
S a emen processed.
.Da aba eS a .c m
PL/SQL T ial
LOOP
o r_code;
END LOOP;
We hen ha e EXIT WHEN c rsor_name%no fo nd, hich means he loop ill e i once here
are no more ro s fo nd in he c rsor.
The impor an par abo his code is ha he FETCH s a emen ill fe ch he ne ro from he
c rsor. This means i fe ches one ro a a ime.
DECLARE
l_fname VARCHAR2(50);
CURSOR c_person IS
BEGIN
OPEN c_person;
LOOP
END LOOP;
.Da aba eS a .c m
PL/SQL T ial
CLOSE c_person;
END;
We open he c rsor
We s ar he loop
We o p he al e of l_fname
This migh seem like a lo of code j s o ri e o some al es o he screen, and i is. I 's simpler o
j s do his as a SELECT s a emen . B his is j s o demons ra e he concep s. Yo can se an code
in o r PL/SQL program ins ead of ri ing he al es o screen.
S a emen processed.
DECLARE
l_fname_1 VARCHAR2(50);
l_fname_2 VARCHAR2(50);
l_fname_3 VARCHAR2(50);
..
.Da aba eS a .c m
PL/SQL T ial
Arra s are a concep in programming here a single ariable s ores m l iple al es. Each of he al es
are accessed sing an inde n mber. The concep orks like his:
DECLARE
BEGIN
o r_code;
END;
The code incl des o lines o se p o r arra : crea ing a pe, and crea ing he ariable.
In PL/SQL, o se an arra , o need o declare he pe of arra firs . This is done sing he TYPE
s a emen . In o her programming lang ages, he arra declara ion and pe are done on a single line,
b in PL/SQL he are on separa e lines.
I sa s ha o are crea ing a TYPE, and he name of his pe e ha e called fname_arra _ pe. This is
j s a name e made p, b i 's clear i 's a pe. I co ld ha e called i archar_ pe or some hing else
o indica e ha i is.
.Da aba eS a .c m
PL/SQL T ial
No ha ? We pop la e he arra .
DECLARE
BEGIN
END;
Wha can e do i h hese al es no ? We can se a FOR loop o loop hro gh hem and ri e hem
o he screen. We can do a lo more i h hese al es, b for his e ample, e'll j s ri e hem o he
screen o keep i simple.
DECLARE
BEGIN
END LOOP;
END;
The code e ha e added is he FOR loop. As e learned in an earlier sec ion, he FOR loop s ar s a a
n mber and ends a ano her n mber. In his e ample, he ariable is called "i", and i s ar s a 1 and
ends a some hing called fname_arra .co n .
.Da aba eS a .c m
PL/SQL T ial
Inside he loop, e sho he al e b sing fname_arra (i), hich means e are referring o a single
elemen inside he arra . We are referring o he elemen i h an inde posi ion of ha e er "i" is
eq al o, hich changes each ime he loop is r n.
If e r n he code, his is ha e ge :
S a emen processed.
Concl sion
Oracle offers o pes of c rsors: an implici and an e plici c rsor. Implici c rsors are crea ed
a oma icall i ho o doing an hing. E plici c rsors are specified b o b o ha e more
con rol o er hem.
Arra s are pes of ariables ha allo o o s ore man al es in a single ariable. The are declared
as a TYPE firs , and hen he arra ariable is declared. The can be accessed sing a n mber ha
represen s heir inde , and are of en done sing loops.
Q i
Q es ion 1
c rsor_name IS selec _q er ;
c rsor_name := selec _q er ;
Q es ion 2
.Da aba eS a .c m
PL/SQL T ial
Q es ion 3
Q es ion 4
Yo can' .
.Da aba eS a .c m
PL/SQL T ial
The e are all grea fea re of he PL/SQL lang age and ill ake o r code o he ne le el.
Field T pe
DECLARE
l_fname VARCHAR2(50);
BEGIN
SELECT fname
INTO l_fname
FROM person;
END;
The l_fname ariable i a VARCHAR2(50). Thi j happen o be he ame a he able e crea ed:
fname VARCHAR2(50)
);
The TYPE a rib e ill le o declare a ariable ba ed on he pe of a col mn in a able. Thi mean
i i a oma icall linked o, or e he ame a a col mn ha e i . There' no need o look p he da a
pe man all or change he code if o r able change .
DECLARE
.Da aba eS a .c m
PL/SQL T ial
BEGIN
Af er pecif ing he ariable name, o pecif he col mn and able name epara ed b a period. Yo
hen pecif %TYPE, hich indica e ha o r ariable ha he ame pe a hi col mn.
DECLARE
l_fname person.fname%TYPE;
BEGIN
SELECT fname
INTO l_fname
FROM person;
END;
The o p of hi code i :
Statement processed.
fname VARCHAR2(50),
lname VARCHAR2(50),
salar NUMBER(8)
);
.Da aba eS a .c m
PL/SQL T ial
We ha e one record:
DECLARE
l_fname person.fname%TYPE;
l_lname person.lname%TYPE;
BEGIN
FROM person;
END;
We ha e ed hree ariable (one for each col mn), each rela ed o he col mn in he able.
The o p of hi code i :
Statement processed.
Ro T pe
In he e ample abo e, e had hree epara e ariable for each of he differen col mn :
DECLARE
l_fname person.fname%TYPE;
l_lname person.lname%TYPE;
BEGIN
.Da aba eS a .c m
PL/SQL T ial
DECLARE
ariable_name table_name%ROWTYPE;
BEGIN
We don' need o pecif an col mn name here: j he ariable name, he able o ba e i on, and
%ROWTYPE.
Le ' ee an e ample:
DECLARE
BEGIN
FROM person;
END;
● There i a ingle ariable called l_ro _per on, hich ha a pe eq al o he per on able ( ing
%ROWTYPE).
● The SELECT INTO i elec ing he col mn al e in o epara e a rib e of he l_ro _per on
ariable, one for each col mn.
Thi re l in le code and eem ea ier o read. I can make a big difference in larger program .
The o p of hi code i :
.Da aba eS a .c m
PL/SQL T ial
END;
Statement processed.
We'll learn abo he o pe of collec ion in hi ec ion: an Inde B Table and a Ne ed Table.
Inde B Table
ariable_name t pe_name;
In hi code, e declare a pe, and hen a ariable of ha pe. The pe ha a name ha e can
pro ide, and e pecif he da a pe of he elemen and he da a pe of he inde .
An e ample of hi fea re i :
DECLARE
name_list first_name;
BEGIN
.Da aba eS a .c m
PL/SQL T ial
..
END;
name_list(1) := 'John';
DECLARE
name_list first_name;
BEGIN
name_list(1) := 'John';
name_list(3) := 'Mark';
name_list(4) := 'Debra';
END;
DECLARE
name_list first_name;
c rrent_name_id PLS_INTEGER;
BEGIN
name_list(1) := 'John';
name_list(3) := 'Mark';
name_list(4) := 'Debra';
c rrent_name_id := name_list.FIRST;
.Da aba eS a .c m
PL/SQL T ial
END LOOP;
END;
● The name_li .FIRST ill re rn he inde of he fir elemen , hich ha been ored in he
c rren _name_id ariable;
The o p of hi code i :
Statement processed.
U ing o r per on able from earlier, hi code ill elec he da a from ha able in o he collec ion:
DECLARE
CURSOR c_person IS
person_list col_person;
ro co nter PLS_INTEGER := 0;
BEGIN
ro co nter := ro co nter + 1;
.Da aba eS a .c m
PL/SQL T ial
END LOOP;
END;
The o p ill ho :
Statement processed.
Ne ed Table
A ne ed able in PL/SQL i ano her pe of collec ion. I ' er imilar o an Inde B Table, e cep i
al a ha an in eger for an inde . I doe no ha e an INDEX BY cla e;
ariable_name t pe_name;
DECLARE
name_list first_name;
BEGIN
END LOOP;
END;
The o p of hi code i :
Statement processed.
.Da aba eS a .c m
PL/SQL T ial
We' e learned abo Inde B Table , Ne ed Table , and Varra . Ho do e kno hen o e each
of hem?
● When o ha e a mall look p able, a i ' crea ed each ime in memor hene er o r n
o r code
When o e a Ne ed Table:
When o e a Varra :
B lk Collec
O r PL/SQL code of en con ain PL/SQL code (declaring ariable , loop , IF a emen ) and SQL code
(SELECT, INSERT, UPDATE). Thi make o r program q i e po erf l.
Each ime an SQL a emen i r n from PL/SQL, a "con e i ch" i performed. The er er i che
from r nning he PL/SQL code o r nning he SQL code. Thi in ol e a mall amo n of ork b he
er er. Thi ma no be no iceable i h one a emen , b if o 're r nning h ndred or ho and of
a emen , acro man er , hen i can reall add p.
Here' o r e p da a.
.Da aba eS a .c m
PL/SQL T ial
INSERT INTO person (fname, lname, salar ) VALUES ('S san', 'Jones',
30000);
BEGIN
UPDATE person p
END LOOP;
END;
The o p i :
1 ro (s) pdated.
Name: John
Name: S san
Name: Mark
Name: Debra
S an Jone 31000
.Da aba eS a .c m
PL/SQL T ial
DECLARE
BEGIN
SELECT fname
FROM person;
UPDATE person p
END LOOP;
.Da aba eS a .c m
PL/SQL T ial
END;
The o p i :
1 ro (s) pdated.
Name: John
Name: S san
Name: Mark
Name: Debra
FORALL in PL/SQL
The UPDATE a emen in he earlier code i r n each ime d ring he loop. Thi mean ha here i a
con e i ch be een PL/SQL and SQL each ime he a emen i r n. In hi e ample i happen 4
ime , b in a real da aba e i can happen h ndred or ho and of ime .
If o can p o r SQL code o ide he loop, hen ha i be er. The code ill onl r n once on all he
ro ha need o be pda ed.
In PL/SQL, he FORALL a emen ill ell he da aba e o genera e and r n all of he DML a emen
ha o ld ha e been genera ed epara el and r n hem a once. Thi red ce he ime aken and he
con e i che .
DECLARE
BEGIN
SELECT fname
.Da aba eS a .c m
PL/SQL T ial
FROM person;
FORALL i IN 1 .. name_list.co nt
UPDATE person p
END;
DECLARE
BEGIN
SELECT fname
FROM person;
FORALL i IN 1 .. name_list.co nt
UPDATE person p
END;
S an Jone 30000
.Da aba eS a .c m
PL/SQL T ial
S an Jone 31000
Concl ion
Field and record pe are hand fea re of PL/SQL and allo o o declare ariable ba ed on he
pe of a col mn or an en ire ro in a da aba e able. The impro e he main ainabili of o r code.
PL/SQL al o allo o o e collec ion . The e are imilar o arra b ha e ome o her ad an age .
The o pe of collec ion are Inde B Table and Ne ed Table.
R nning SELECT a emen or o her DML a emen indi id all can impac he performance of
o r code. I ' be er o i ch be een PL/SQL and SQL a li le a po ible. The BULK COLLECT and
FORALL fea re allo o o do ha in a be er a .
Q i
Q e ion 1
Q e ion 2
.Da aba eS a .c m
PL/SQL T ial
Q e ion 3
UPDATE emplo ee
END LOOP;
Q e ion 4
Wh ho ld o e BULK COLLECT?
.Da aba eS a .c m
PL/SQL T ial
Cha e 7: Ne ed Bl ck a d Package
A nested block is here a block of PL/SQL code is nested inside another block. A PL/SQL block is a set
of code inside the DECLARE, BEGIN, and END ke ords. Inside the BEGIN and END ke ords, o
can place another block, hich is the nested block.
● To keep the code foc sed on one area. A nested block ma contain the code and logic for a
smaller part of o r o erall code.
DECLARE
o _ a iable ;
BEGIN
o _code;
END;
DECLARE
o _ a iable ;
BEGIN
o _code;
[DECLARE
mo e_ a iable ;]
BEGIN
mo e_code;
END;
.Da aba eS a .c m
PL/SQL T ial
e en_mo e_code;
END;
Yo r second BEGIN and END block is inside the first BEGIN and END block. Yo can ha e code before
and after this nested block, and code inside the nested block. The DECLARE section inside the nested
block is optional.
DECLARE
BEGIN
SELECT ala
INTO l_ ala
FROM e on
BEGIN
UPDATE e on
DBMS_OUTPUT.PUT_LINE('Sala da ed.');
EXCEPTION
END;
END;
In this code, e are selecting a salar al e for John into a ariable called l_salar .
Then, inside the nested block, e are r nning an UPDATE statement to pdate the salar , and then
riting a message. If this nested block fails, then e rite a message e plaining the error that
happened.
.Da aba eS a .c m
PL/SQL T ial
This is done so that the UPDATE statement can r n and an errors are handled separatel . If there is
an iss e pdating the data, an error is sho n, b t the rest of the code keeps r nning.
1 o ( ) da ed.
Sala da ed.
Mo e code he e.
If e change the code to make an error occ r on the UPDATE statement, this is hat happens:
DECLARE
BEGIN
SELECT ala
INTO l_ ala
FROM e on
BEGIN
UPDATE e on
DBMS_OUTPUT.PUT_LINE('Sala da ed.');
EXCEPTION
END;
END;
The o tp t is sho n:
1 o ( ) da ed.
.Da aba eS a .c m
PL/SQL T ial
Mo e code he e.
This error is sho n beca se the UPDATE statement enco ntered an error. The error as handled b
an e ception and ritten to the screen. The rest of the code kept r nning (the p t_line f nction that
rote "More code here").
A package in PL/SQL is an object that gro ps logicall related PL/SQL code. The ha e t o parts: a
package specification that defines the p blic interface for the package, and a package bod hich
contains the code req ired for each proced re inside the package.
If o ha e e perience in other programming lang ages, o can think of a package as being similar
(b t not the same as) a librar . It contains m ltiple related proced res and the code can be called from
other PL/SQL code.
Earlier in this g ide, e j st learned ho to create proced res and f nctions. These objects are
created on the database, b t are standalone objects and are not inside packages. We'll learn ho to
create packages in this g ide.
Wh se Packages?
Ea ie de ig a lica i : Yo can rite the specification first (the names and parameters) of the
packages and proced res, and ork on the bod (the implementation details or code) later, if o like.
Be e e f a ce: Package code is loaded into memor hen the code is first r n. Whene er an
other code in the package is r n, it's accessed from memor . This means it's faster than reading and
r nning the code from the disk.
Hide he de ail : Yo can pro ide access to the specification (proced re names and parameters)
itho t pro iding the details of ho the ork. Yo can change the details hene er o ant, and
the code that refers to the package does not need to change.
M d la de el e : Yo can combine all of the related code into a package to make it easier to
de elop o r application. Interfaces bet een packages can be de eloped and each package can be
self-contained, similar to ho classes ork in object-oriented programming in other lang ages.
A package in PL/SQL contains t o parts: a package specification and a package bod . Let's take a look
at hat these are.
.Da aba eS a .c m
PL/SQL T ial
A package specification in PL/SQL is here p blic code is declared for a package. It contains an
ariables, f nctions, and proced res that o ant others to kno abo t and access. The f nctions
and proced res contain the parameter names and t pes. This is so other sers and programs can
access them and r n them, itho t kno ing the details of ho the ork.
Yo se the CREATE PACKAGE statement. It contains the name of the package and an code o
ant to incl de in the package specification.
For e ample, a package for calc lating c stomer order shipping information co ld be:
END o de _ hi ing;
If o 're calling this proced re, this is all o need to kno . Yo pass the al e for the co ntr and the
shipping is calc lated.
A package bod contains the implementation details, or code, that the package specification req ires.
This incl des the code for each of the proced res or f nctions, and details of c rsors. This is here the
code inside each of the proced res and f nctions go.
A package bod is created ith the CREATE PACKAGE BODY statement. The declarations of the
objects in the bod m st match those of the specification (proced re names, parameters).
Follo ing on from the earlier e ample, e can rite a package bod that details hat the
calc_shipping f nction does:
BEGIN
SELECT hi ing_fee
INTO l_fee
FROM hi ing_look
.Da aba eS a .c m
PL/SQL T ial
END;
END o de _ hi ing;
This code looks p the shipping fee from a table and displa s it on the screen. If o r n this code, it ill
create the package bod for this package.
Note: If o ant to drop a package to make changes and create it again, r n DROP PACKAGE
package_name.
o ce_co n VARCHAR2(100),
hi ing_fee NUMBER(10,2)
);
INSERT ALL
.Da aba eS a .c m
PL/SQL T ial
USA USA 5
USA UK 18
USA France 20
USA Canada 7
To r n o r package code, o refer to the package name and proced re name in PL/SQL:
BEGIN
o de _ hi ing.calc_ hi ing('UK');
END;
The o tp t e get is
This sho s the shipping fee is 18, hich is hat o r table sho s. When e call the package, e don't
care ho the shipping fee is calc lated, e onl ant to get the al e.
● Ret rn the shipping_fee al e from the proced re, rather than sho it sing PUT_LINE.
● If the majorit of shipping is done from USA b t some is done from another co ntr , perhaps
add the so rce co ntr as another parameter.
So that's ho o can create a package in PL/SQL. First create the package object, then the package
bod ith the details. The packages can then be r n from an PL/SQL code block.
Concl sion
A nested block is a BEGIN/END block ithin another BEGIN/END block. The are sef l for
containing related code and for handling errors itho t impacting the entire program.
Packages are sed to contain related f nctionalit , s ch as ariables and proced res. The help ith
application design and performance. A package specification contains the p blic interface, or hat
.Da aba eS a .c m
PL/SQL T ial
other sers can see, s ch as the proced re names and parameters. The package bod contains the
details of the proced res, incl ding the code inside them.
Q i
Q estion 1
Can o ha e a BEGIN and END block ithin another BEGIN and END block?
Q estion 2
What is the difference bet een a package specification and a package bod ?
● A package specification contains the details of f nctions, and a package bod contains onl the
names and parameters.
Q estion 3
END em _calc;
BEGIN
UPDATE em
.Da aba eS a .c m
PL/SQL T ial
WHERE id = em _id;
END;
END em _calc;
Q estion 4
What happens if an error is fo nd in a nested block, and it is handled b the EXCEPTION section and is
passed to a DBMS_OUTPUT.PUT_LINE f nction?
● The error is raised in the main block as ell, and if it is not handled, it ill ca se an error in the
entire program.
● The error is raised in the main block and ca ses an error there, regardless of hat code e ists.
.Da aba eS a .c m
PL/SQL T ial
Tha k agai !
Be B
.Da aba eS a .c
Q A
Cha e 1
Q e i 1:
Wha d e PL/SQL a d f ?
● P e f L ad fS c ed Q e La g age
● P L S Q L
● P i ab e La g age S c ed Q e La g age
Q e i 2:
Wha ke di ed a he e ec ab e ec i f a PL/SQL g a ?
● START
● RUN
● BEGIN
● END
Q e i 3:
Wha i he b i -i f ci ed f di a i g he c ee ?
● PRINTLN
.Da aba eS a .c m
PL/SQL T ial
● WRITE
● SAVE
● P T LINE
Q e i 4:
Wha ' i i gf hi i e He W d g a ?
BEGIN
DBM O . LINE
END;
● The e i START ke d.
● T P T LINE .
● N hi g, i i cce f .
● The e i f ci ca ed PUT_LINE.
Cha e 2
Q e i 1:
● START
● BEGIN
● DECLARE
● VARIABLE
Q e i 2:
● T .
● The a e, da a e, a d he a e a e a e i ed
Q e i 3:
.Da aba eS a .c m
PL/SQL T ial
Wha i a c a ?
● A a ea i e ha e a a ef g a a d ca be cha ged i g a .
● A .
● Af ci ha di a da a he c ee .
● A a j i a e ge he i e.
Q e i 4:
DECLARE
_ adi NUMBER(8);
BEGIN
END;
● T , ' .
● The c de i a d di a a a e f 2.
Cha e 3
Q e i 1:
Wha i he ke d ed a a f a IF a e e ha c de if e f he ided c di i
a e e?
● ELSE
● OTHERWISE
● FINAL
● END
.Da aba eS a .c m
PL/SQL T ial
Q e i 2:
Wha d e he FOR a e e d ?
● I i ia i e a a iab e
● Check if a c di i i e fa e, a d he c de i ide e i e if i i e
● S
● Se he da a e i ed e d a e ai
Q e i 3:
Q e i 4:
Wha i g i h hi c de?
DECLA E
N MBE (3) := 8;
BEGIN
:= + 1;
END LOO ;
END;
● I .
● N hi g, i i cce f a d h fi e i e f .
● I i b ca e a i fi i e .
● I i a d h eigh i e f .
.Da aba eS a .c m
PL/SQL T ial
Cha e 4
Q e i 1
● The a e b h he a e.
● F RET RN , ' .
● P ced e ca be ed i eg a SQL, b f ci ca .
Q e i 2
● I
.
● N hi g, hi ke di a id.
● N hi g, i ' a a id ke db d e a ced e f ci .
● I de e i e if c de i i e e da a i a ab e da e e i i g da a.
Q e i 3
Wha i a e ce i ?
● A e ha ha e he c ea e ced e f ci , ch a a i i g b acke .
● The a f a IF a e e ha if c i e ia a e e.
● A .
● Ac ec i f da a ha i i e ed i a ab e.
Q e i 4
H ca he c de i a ced e?
● R "CALL " .
.Da aba eS a .c m
PL/SQL T ial
● Y ca ' ced e , ca f ci .
Cha e 5
Q e i 1
H ca dec a e a e ici c ?
● IS ;
● c _ a e := e ec _ e ;
● c _ a e IS TYPE OF e ici _c ;
Q e i 2
Wha d e he %FOUND a ib e f a c d ?
● Re he da a f he c .
● Re he be f f db he c
● R ,
Q e i 3
Wha d e hi c de d ?
● N hi g, i i h a e
● I ,
● I c ea e a e ab e i h c , e a a a a a d he he a a be .
Q e i 4
● %RO CO NT .
● SELECT f he ab e fi d i e ed da .
.Da aba eS a .c m
PL/SQL T ial
● Y ca ' .
● U e he %NUMROWS a ib e.
Cha e 6
Q e i 1
Wha d e %TYPE e d ?
● N hi g, i ' a a id c a d i PL/SQL.
● I .
● I e dec a e a a iab e ha i ba ed he da a e fa c i a ab e.
Q e i 2
● A I B T .
● N hi g, he a e b h he a e
● A Ne ed Tab e k i h e ed SQL a e e
● A I de B Tab e eed a ab e i h a i de i.
Q e i 3
Wha ' g i h hi c de (a i g he e _i e i a d he e ee ab e e i )?
FO ALL IN 1 .. . LOO
DA E
E = + 1
HE E = . ;
END LOO ;
.Da aba eS a .c m
PL/SQL T ial
● N hi g, i i cce f .
Q e i 4
Wh h d e BULK COLLECT?
● T PL/SQL SQL .
● Y h d ' ei a a a i ' .
● T ge da a f a ge ab e , b a ab e .
Cha e 7
Q e i 1
● , .
● Ye , b if b h b ck c ai a DECLARE ec i .
● Ye , b ca ha e a he .
● N , hi i a ed i PL/SQL.
Q e i 2
● N hi g, he a e d ha ea he a e hi g.
● A , .A
.
Q e i 3
C EA E ACKAGE A
OCED E ( N MBE );
.Da aba eS a .c m
PL/SQL T ial
END ;
C EA E ACKAGE BOD A
OCED E ( N MBE ) A
BEGIN
DA E
E = * 0.1
HE E = ;
END;
END ;
● N hi g, i k fi e.
● T .
Q e i 4
● The e i ai ed i he ai b ck a e , a d if i i ha d ed, i i ca e a e i he
e i e g a .
● N , .
● Thi i a id a e ca ' be ha d ed i e ed b ck .
● The e i ai ed i he ai b ck a d ca e a e he e, ega d e f ha c de e i .
.Da aba eS a .c m