0% found this document useful (0 votes)
24 views

PLSQL Tutorial

Uploaded by

yacine.benjdidia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

PLSQL Tutorial

Uploaded by

yacine.benjdidia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 120

PL/SQL T ial

Learn he ba ic of PL/SQL

Be B
.da aba e a .c
PL/SQL T ial

Are o interested in learning PL/SQL?

Yo ' e come to the right place.

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?

● It's eas to follo .

● Yo 'll start riting o r first PL/SQL program er earl , before reading a ton of pages on
theor .

● It incl des q i q estions and ans ers.

● It incl des code samples hich o can r n o rself.

● It looks great.

● There are no ads.

Table of Contents

What's incl ded in this t torial?

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.

C 3: C (IF THEN ELSE) .

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.

F rther Reso rces


If o ' e finished this t torial and ant more places to learn PL/SQL, check these o t:

● 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.

Let's get started ith Chapter 1!

.Da aba eS a .c m
PL/SQL T ial

C 1: I Y F PL/SQL P

In this chapter, o 'll learn:

● What PL/SQL is and hat it stands for

● The basic str ct re and s nta of a PL/SQL program

● Write and r n o r first PL/SQL program

Let's get right into it!

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:

● Updating ser profiles ith an UPDATE statement

● Displa ing for m posts ith a SELECT statement

● Sho ing bank transactions ith a SELECT statement

● Adding ne prod cts ith an INSERT statement

What abo t all the b siness logic that is needed along ith this?

B siness logic is needed for things s ch as:

● Checking for e isting sers before adding a ne ser

● Validating acco nt n mbers are alid

● 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.

The Basic Str ct re of a PL/SQL Program

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.

A PL/SQL program incl des se eral blocks:

● 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.

● E ception section: this defines hat happens if something goes rong.

.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.

Ho do e create these blocks? We se special ke ords.

BEGIN and END

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

-- o r code goes here

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.

Ho can o r n PL/SQL code? There are a fe places:

● A command line (s ch as SQL*Pl s or SQLcl)

● An IDE (s ch as SQL De eloper or Toad)

Where o r n this code depends on ho o can access an Oracle database.

● 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.

● Use Oracle Li eSQL, Oracle's free eb-based SQL editor.

In this t torial, e'll be sing Li eSQL as it's the easiest to get started on.

Open Li eSQL

Here's ho to get started ith Li eSQL:

1. Bro se to ​https://li esql.oracle.com

.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.

4. On the Create Acco nt page, fill o t the form ith o r details.

.Da aba eS a .c m
PL/SQL T ial

5. Once o ha e created o r acco nt, log in to Li e SQL sing these details.

The SQL Worksheet is then displa ed. This is here o can r n SQL statements and see o r o tp t.

No , let's rite o r first PL/SQL program.

Yo r First PL/SQL Program: Hello World

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.

Enter this code onto the SQL Worksheet:

.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.

No , ho to e displa data to the screen? We se a f nction called PUT_LINE.

To call the PUT_LINE f nction, e need to specif t o things:

● The package that the f nction is contained in

● The te t e ant to displa .

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".

The line to incl de looks like this:

DBMS_OUTPUT.PUT_LINE('Hello World');

Yo r program ill look like this:

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.

So, o r Li eSQL indo sho ld look like this:

.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)

Congrat lations! Yo ' e j st ritten o r first PL/SQL program!

Ne t, o 'll learn abo t the declarati e section in PL/SQL and ho to se ariables.

Q i

First, test o r kno ledge ith a q i .

Q estion 1:

What does PL/SQL stand for?

● Po erf l Loads of Str ct red Q er Lang age

● Proced ral Lang age Str ct red Q er Lang age

● Packaged Lang age Str ct red Q er Lang age

● Printable Lang age Str ct red Q er Lang age

.Da aba eS a .c m
PL/SQL T ial

Q estion 2:

What ke ord is sed to start the e ec table section of a PL/SQL program?

● 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:

What's missing from this simple Hello World program?

BEGIN

DBMS_OUTPUT.PUT_LINE

END;

● There is no START ke ord.

● There is no te t al e or brackets for the PUT_LINE f nction.

● Nothing, it ill r n s ccessf ll .

● There is no f nction called PUT_LINE.

.Da aba eS a .c m
PL/SQL T ial

Chap e 2: Va iable and Ope a o


In hi cha e , o 'll lea n:

● Wha a iable a e and ho o e hem in PL/SQL

● Diffe en da a e of he e a iable

● O e ao and ho PL/SQL handle hem

O P e io Code

The code f om he e io le on looked like hi :

BEGIN

DBMS_OUTPUT.PUT_LINE('Hello World');

END;

I o e he e "Hello Wo ld" o he c een.

Wha if o an ed o change ha e ?

Yo can j change ha ' in ide he f nc ion a ame e :

BEGIN

DBMS_OUTPUT.PUT_LINE('I am learning');

END;

Thi ill di la he changed e a an o hen o n he og am.

Statement processed.

I am learning

One a o im o e hi code i o o e he e e an o o in a a iable. PL/SQL o he


e of a iable , j like an o he og amming lang age.

A a iable i a named a ea in memo ha o e he da a o ell i o o e. The a e ed o e a a e


he al e of ome hing f om he ea men of ha al e. Thi mean o can ea il change he al e of
he o e i ho al e ing he f nc ion. I al o im o e eadabili of he code.

Fi , e need o lea n abo he decla a i e ec ion.

The Decla a i e Sec ion in PL/SQL

Ea lie in hi o ial e men ioned he e e e e e al ec ion of a PL/SQL og am:

.Da aba eS a .c m
PL/SQL T ial

● Decla a i e ec ion: hi i he e a iable a e decla ed

● E ec able ec ion: hi i he code ha i na a of he og am goe .

● E ce ion ec ion: hi define ha ha en if ome hing goe ong.

The e ec able ec ion i defined i h BEGIN and END.

The decla a i e ec ion i defined i h he ke o d DECLARE. I goe befo e he BEGIN ke o d:

DECLARE

BEGIN

DBMS_OUTPUT.PUT_LINE('I am learning');

END;

Wha i he DECLARE ec ion fo ? We e i o decla e a iable in PL/SQL. A a iable ha a name, a


da a e, and a al e.

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​.

O code look like hi o fa :

DECLARE

l_text

BEGIN

DBMS_OUTPUT.PUT_LINE('I am learning');

END;

We hen ha e o ecif he da a e of hi l_ e a iable. All a iable need a da a e o O acle


kno ha kind of da a i con ain .

We an o o e he al e ha e' e going o e in he PUT_LINE f nc ion, hich i a e al e, o


e ho ld e he VARCHAR2 da a e. Decla ing a VARCHAR2 da a e i he ame in PL/SQL a
ecif ing a col mn e in SQL, o e need a ma im m leng h. Le ' e 50 fo hi e am le.

O code hen look like hi :

DECLARE

l_text VARCHAR2(50)

BEGIN

DBMS_OUTPUT.PUT_LINE('I am learning');

END;

.Da aba eS a .c m
PL/SQL T ial

We' e almo he e. No , e need o ecif ha l_ e i e al o. We do hi b adding a colon, an


e al ign, hen he ne al e, hen a emicolon. We'll e he al e of "Hello Wo ld". O code look
like hi :

DECLARE

l_text VARCHAR2(50) := 'Hello World';

BEGIN

DBMS_OUTPUT.PUT_LINE('I am learning');

END;

O code no ha he a iable called l_ e , hich i of e VARCHAR2 i h a ma im m of 50


cha ac e . I ha been e o he al e of "Hello Wo ld".

No , add hi code o o SQL o k hee .

R n he code ing he R n b on. The o look like hi :

Statement processed.

I am learning

Hang on e added ha line abo he a iable, b he o ill ho he o d "I am lea ning"?


Ho did ha ha en?

Thi ha ha ened beca e e en ho gh e added he a iable, e didn' change o code o e ha


a iable. The a ame e in ide he PUT_LINE f nc ion ill a "I am lea ning".

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

l_text VARCHAR2(50) := 'Hello World';

BEGIN

DBMS_OUTPUT.PUT_LINE(l_text);

END;

No , n hi code:

Statement processed.

Hello World

Yo 'll ee he o d "Hello Wo ld" in he o ec ion again. Yo can no change he al e of l_ e


o ha e e o an , and i ill be i en o he c een.

Wh i hi ef l? I ill hel la e hen e o k on mo e com lica e og am , a i im o e


eadabili and allo o mani la e he e al e in he f e.

.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 .

A g ea a o im o e eadabili i o inden o line of code. Thi i commonl done in o he


og amming lang age , and i al o a good idea in PL/SQL. Whe he o e ab o ace , inden
o, h ee, o fo cha ac e , inden ing o code make i ea ie o ead and o k i h.

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

l_text VARCHAR2(50) := 'Hello World';

BEGIN

DBMS_OUTPUT.PUT_LINE(l_text);

END;

In hi o ial I'll be inden ing o ace , b i' o o ho m ch o inden . A long a i '


con i en !

Yo 'll al o no ice ha I e ace befo e and af e o e a o , ch a he := mbol . Thi i no


e i ed, b I hink i make he code mo e eadable. Yo 'll find I add ace in man lace in he
code fo hi ea on.

Defining Va iable Wi ho A igning Them

In o ea lie code, e decla ed a a iable (added a a iable and a da a e) and a igned a al e o i .

Ho e e , in PL/SQL, e can decla e a iable i ho a igning a al e o i a he ame ime. Thi i


ef l if o an o e a a iable fo ome hing b don' kno ha he al e ho ld be a he ime
of decla ing he a iable.

Yo can decla e he name and e of he a iable i ho gi ing i a al e, like hi :

DECLARE

l_text VARCHAR2(50);

BEGIN

DBMS_OUTPUT.PUT_LINE(l_text);

END;

A long a he a iable ha a name and a da a e, and end i h a emicolon, i ill o k. Ho e e , if


e n hi code, hi i ha e ge :

Statement processed.

.Da aba eS a .c m
PL/SQL T ial

The e i no o . Thi i beca e he a iable of l_ e i no e , o he PUT_LINE f nc ion doe no


i e an hing.

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

l_text := 'Hello World';

DBMS_OUTPUT.PUT_LINE(l_text);

END;

Thi ne code ha a igned he al e of "Hello Wo ld" o he a iable l_ e . The o of hi code


no look like hi :

Statement processed.

Hello World

The o no incl de he e , beca e e ha e a igned i o he a iable ha a ed, befo e


he PUT_LINE a emen i n.

If e a ign he a iable af e he PUT_LINE a emen , hen he o i nchanged, beca e he


PUT_LINE a emen i called befo e he al e i changed.

DECLARE

l_text VARCHAR2(50);

BEGIN

l_text := 'Hello World';

DBMS_OUTPUT.PUT_LINE(l_text);

l_text := 'Something else';

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

Te al e a en' he onl a iable o can e in PL/SQL. Yo can e an da a e a ailable in


O acle SQL, a ell a a fe ha a e PL/SQL ecific.

Le ' look a ome n mbe da a e . We can c ea e a a iable i h he e of NUMBER, and e


PUT_LINE o i e i o he c een.

Thi code doe e ac l ha :

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

The PUT_LINE f nc ion acce n mbe a ell a e . If e an o change he al e ha i ed in


hi og am, e j e lace he 12 i h o ne n mbe .

DECLARE

l_mynumber NUMBER(8);

BEGIN

l_mynumber := 491;

DBMS_OUTPUT.PUT_LINE(l_mynumber);

END;

Statement processed.

491

Conca ena ion

In o ea lie e am le, e e he al e of a a iable, and ed ha a he o . Di la ing he


n mbe 12 o 491 a n' ha ef l b i elf. Wha if e an ed o add mo e e o he o ?
In ead of ho ing "491", ha if e an ed o a "The n mbe o cho e a 491"?

We can do ha ing a fea e called conca ena ion.

Wha i conca ena ion?

.Da aba eS a .c m
PL/SQL T ial

Conca ena ion i he abili o join o al e oge he in o one. I ' of en ed o combine al e in o


a ingle o . Man og amming lang age o i ing diffe en cha ac e , ch a &, o a .
cha ac e . Conca ena ion can al o be done i h f nc ion .

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.

To add he e "The n mbe o cho e a " o he o , e can conca ena e ha e i h he


l_m n mbe a iable:

DECLARE

l_mynumber NUMBER(8);

BEGIN

l_mynumber := 491;

DBMS_OUTPUT.PUT_LINE('The number you chose was ' l_mynumber);

END;

R nning hi code gi e hi e l:

Statement processed.

The number you chose was 491

The f ll o ho he e e added along i h he al e of he a iable.

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;

DBMS_OUTPUT.PUT_LINE('The number you chose was' l_mynumber);

END;

Statement processed.

The number you chose was491

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.

Le ' a o an ed o add o n mbe oge he in PL/SQL. Yo code co ld look like hi :

DECLARE

l_mynumber NUMBER(8);

BEGIN

l_mynumber := 4 + 9;

DBMS_OUTPUT.PUT_LINE('The number you chose was ' l_mynumber);

END;

Thi code e he al e of l_m n mbe o he al e of 4 l 9. Thi i e o 13, hich i ho n in he


o if o n he code.

Statement processed.

The number you chose was 13

Yo can e diffe en n mbe al e and add hem oge he in hi a .

S b ac ing N mbe

If o an o b ac n mbe in PL/SQL, o can e he - mbol o b ac one n mbe f om he


o he .

The follo ing code ill b ac 5 f om he n mbe 100 and di la he o .

DECLARE

l_mynumber NUMBER(8);

BEGIN

l_mynumber := 100 - 5;

DBMS_OUTPUT.PUT_LINE('The number you chose was ' l_mynumber);

END;

The o look like hi :

Statement processed.

The number you chose was 95

M l i l ing N mbe

.Da aba eS a .c m
PL/SQL T ial

Yo can m l i l n mbe in PL/SQL b ing he * mbol. Thi i ed in man og amming


lang age fo m l i lica ion. I ' ed in SQL fo elec ing all col mn , b if i ' ed in an e e ion
in SQL o in PL/SQL, i ' ea ed a a m l i lica ion.

The follo ing code ill m l i le 20 b 4 and di la he o .

DECLARE

l_mynumber NUMBER(8);

BEGIN

l_mynumber := 20 * 4;

DBMS_OUTPUT.PUT_LINE('The number you chose was ' l_mynumber);

END;

The o look like hi :

Statement processed.

The number you chose was 80

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;

DBMS_OUTPUT.PUT_LINE('The number you chose was ' l_mynumber);

END;

The o look like hi :

Statement processed.

The number you chose was 25

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

DBMS_OUTPUT.PUT_LINE('The number you chose was ' l_mynumber);

END;

The o look like hi :

Statement processed.

The number you chose was 14

The ea on hi ho 14 i beca e he da a e i decla ed a an 8-digi n mbe . No eci ion i


ecified o i e a eci ion of 0, o nding do n o he nea e n mbe . I ho 100 di ided b 7
hich i 14.29, o nded do n o 14.

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.

O code ma look like hi :

DECLARE

l_radius NUMBER(4, 3);

BEGIN

l_radius := 8;

DBMS_OUTPUT.PUT_LINE('The circumference is ' 2 * l_radius *


3.14159);

END;

O o look like hi :

Statement processed.

The circumference is 50.26544

Thi code incl de a a iable called l_ adi hich i he adi of o ci cle. We e hi al e o 8


in ide o code, and hen o he al e of he ci c mfe ence a 2 * l_ adi * 3.14159.

Le ' e o kno ledge of a iable o decla e a a iable fo he ci c mfe ence, e ha o he


calc la ed al e, and e ha a iable in he o .

DECLARE

l_radius NUMBER(4, 3);

l_circumference NUMBER(10, 3);

.Da aba eS a .c m
PL/SQL T ial

BEGIN

l_radius := 8;

l_circumference := 2 * l_radius * 3.14159;

DBMS_OUTPUT.PUT_LINE('The circumference is ' l_circumference);

END;

O o look like hi :

Statement processed.

The circumference is 50.265

Thi i good, b looking a hi code o migh onde ha he ignificance of he n mbe 3.14159 i .


Thi e am le ma make en e a o migh kno ha i i e al o, b he code ho ld ac all
e lain hi i ho o needing o kno i .

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

l_radius NUMBER(4, 3);

l_circumference NUMBER(10, 3);

l_pi NUMBER(6, 5) := 3.14159;

BEGIN

l_radius := 8;

l_circumference := 2 * l_radius * l_pi;

DBMS_OUTPUT.PUT_LINE('The circumference is ' l_circumference);

END;

The o of hi code i :

Statement processed.

The circumference is 50.265

The code n , e' e ed a iable , and i ' ea o ead.

Wha if, fo ome ea on, e change he al e of i i hin o code?

DECLARE

l_radius NUMBER(4, 3);

l_circumference NUMBER(10, 3);

l_pi NUMBER(6, 5) := 3.14159;

BEGIN

.Da aba eS a .c m
PL/SQL T ial

l_radius := 8;

l_pi := 4;

l_circumference := 2 * l_radius * l_pi;

DBMS_OUTPUT.PUT_LINE('The circumference is ' l_circumference);

END;

We can no code and ge hi o .

Statement processed.

The circumference is 64

The o ho a al e of 64, hich i no co ec acco ding o o le . Thi i beca e e ha e e


i o 4.

I he e an a o e en hi f om being changed in o code af e e ecif i ?

Ye , he e i . We can decla e he l_ i a iable a a con an . A con an i a e of a iable ha i no


allo ed o change d ing he og am. Once i i decla ed and a igned, i can' be changed. I ' g ea
fo al e ha ne e change, ch a i, and o he al e o og am e ha don' change. I hel
e en e o ch a hi .

To decla e a a iable a a con an , e add he ke o d CONSTANT af e he a iable name and


befo e he da a e. The a iable al o need o be defined and a igned a he ame ime.

To e he a iable of l_ i a a con an , o code ill look like hi :

DECLARE

l_radius NUMBER(4, 3);

l_circumference NUMBER(10, 3);

l_pi CONSTANT NUMBER(6, 5) := 3.14159;

BEGIN

l_radius := 8;

l_circumference := 2 * l_radius * l_pi;

DBMS_OUTPUT.PUT_LINE('The circumference is ' l_circumference);

END;

Thi a iable i no a con an . Thi code ill n and ho he igh o :

Statement processed.

The circumference is 50.265

If o o change he al e of l_ i d ing he og am, o 'll ge an e o .

DECLARE

.Da aba eS a .c m
PL/SQL T ial

l_radius NUMBER(4, 3);

l_circumference NUMBER(10, 3);

l_pi CONSTANT NUMBER(6, 5) := 3.14159;

BEGIN

l_radius := 8;

L_pi := 4;

l_circumference := 2 * l_radius * l_pi;

DBMS_OUTPUT.PUT_LINE('The circumference is ' l_circumference);

END;

ORA-06550: line 7, column 3: PLS-00353: expression 'L_PI' cannot be used


as an assignment target

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

In hi cha e , o lea ned:

● Wha a iable a e, ho o decla e hem, and ho o a ign hem

● U ing e and n mbe a iable

● Ho o conca ena e o a iable oge he

● Ho o add, b ac , m l i l , and di ide n mbe

● 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

To e o PL/SQL kno ledge o fa , ake hi i on he o ic co e ed in hi cha e .

Q e ion 1:

Wha ke o di ed o a he ec ion he e a iable a e c ea ed?

● START

● BEGIN

.Da aba eS a .c m
PL/SQL T ial

● DECLARE

● VARIABLE

Q e ion 2:

Wha do o need o incl de hen decla ing a a iable?

● The name of he a iable and he da a ea e e i ed.

● The name, da a e, and he al e a e all e i ed

● The name of he a iable i e i ed.

● The name, da a e, he al e, and he o d CONSTANT a e all e i ed.

Q e ion 3:

Wha i a con an ?

● An a ea in memo ha o e a al e fo o og am and can be changed in o og am.

● A a iable in o og am ha canno be changed once i i e.

● A f nc ion ha di la da a o he c een.

● A a o join o al e oge he in o one.

Q e ion 4:

Wha ' ong i h hi code?

DECLARE

l_radius NUMBER(8);

BEGIN

DBMS_OUTPUT.PUT_LINE('The diameter is ' 2 * l_radius);

END;

● No hing. I ill n and di la he al e of 16, beca e l_ adi i e o 8 and he f nc ion


m l i lie i b 2.

● The code ill n, b i on' di la a n mbe beca e he al e of l_ adi i no e .

● The code ill n and di la a al e of 2.

● The code ill no n beca e o can' conca ena e a e al e i h a n mbe al e.

.Da aba eS a .c m
PL/SQL T ial

Chap e 3: Condi ion and Loop

In hi chap e , o 'll lea n abo :

● Condi ion (If, Then, El e)

● Loop

● Commen ing Code

The e a e common fea e of o he p og amming lang age , and PL/SQL le o e he e fea e


a ell.

Wha A e Condi ion ?

In he code e ha e i en o fa , he da aba e e ec e e e line of code f om op o bo om. Thi i


accep able fo imple p og am . B a o lea n mo e and i e mo e code, o 'll e en all an he
code o do diffe en hing ba ed on diffe en condi ion , ch a :

● Di pla a me age if a e ' acco n balance i belo a ce ain n mbe

● Pe fo m a diffe en ac ion depending on he acco n pe

● Di pla a diffe en al e depending on he loca ion of a e

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

An IF a emen i he e a condi ion i checked, and if i i e, a e of code i n.

Thi can be ep e en ed in PL/SQL code in hi a :

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.

Le ' ake a look a an e ample. We an o find he leng h and id h of a ec angle, and if he a e he


ame, e ill di pla a me age a ing i i a q a e.

DECLARE

l_width NUMBER(5) := 20;

.Da aba eS a .c m
PL/SQL T ial

l_length NUMBER(5) := 20;

BEGIN

IF (l_width = l_length) THEN

DBMS_OUTPUT.PUT_LINE('This is a square.');

END IF;

END;

We ha e o a iable : one fo he leng h and one fo he id h. In ide he BEGIN block, e ha e an IF


a emen .

In ide he b acke of he IF a emen i he condi ion. The condi ion check ha he id h eq al he


leng h, hich i done ing he = ign. If hi calc la ion i e, hen he code in ide n , hich i he
PUT_LINE f nc ion.

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.

Thi me age i ho n beca e he leng h and id h a e eq al. We can change he al e of he


a iable and ee if he o p change .

DECLARE

l_width NUMBER(5) := 20;

l_length NUMBER(5) := 20;

BEGIN

IF (l_width = l_length) THEN

DBMS_OUTPUT.PUT_LINE('This is a square.');

END IF;

END;

Statement processed.

No ice ha he o p doe no a i i a q a e. Thi i beca e he IF a emen doe no e na


e al e, beca e he leng h and id h a e diffe en (18 and 20).

Tha ' a imple IF a emen in PL/SQL: code ha n if a condi ion i e.

.Da aba eS a .c m
PL/SQL T ial

R nning Code When Fal e i h ELSE

In he ea lie e ample, e had ome PL/SQL code ha di pla ed a me age if he al e e e he


ame, and he efo e he hape i a q a e. No hing a di pla ed if he al e e e no he ame.

Wha if e an ed o do ome hing if he e al e e e no he ame, o if he condi ion a fal e?

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 .

Thi can be ep e en ed in PL/SQL code in hi a :

IF (condition) THEN

our_code;

ELSE

our_other_code;

END IF;

Yo impl add he ELSE ke o d af e he code o n if he condi ion i e, hen add code o


an o n if he condi ion i fal e.

Le ' a e an ed o e pand on he ea lie e ample o ho a me age if he leng h and id h i no


eq al. We ill di pla a me age a ing he hape i a ec angle.

O code o ld look like hi :

DECLARE

l_width NUMBER(5) := 20;

l_length NUMBER(5) := 20;

BEGIN

IF (l_width = l_length) THEN

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

l_width NUMBER(5) := 17;

l_length NUMBER(5) := 20;

BEGIN

IF (l_width = l_length) THEN

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.

Checking M l iple Condi ion i h ELSIF

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

l_width NUMBER(5) := -4;

l_length NUMBER(5) := -3;

BEGIN

IF (l_width = l_length) THEN

.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.

We an o do ome hing if he id h al e i nega i e. We o ld need o add ano he check in ide


hi a emen . We can do ha ing he ELSIF ke o d, hich i ho fo "el e if".

In PL/SQL code, he code look like hi :

IF (condition) THEN

our_code;

ELSIF (condition2) THEN

our_second_code

ELSE

our_other_code;

END IF;

The ELSIF goe af e he code ha i n fo he IF a emen , and befo e he ELSE a emen . If he


fi IF condi ion i fal e, hen he condi ion in ide he ELSIF i checked. If ha i e, hen he code
in ide he ELSIF i n, o he i e he ELSE a emen i n.

Le ' e pand o e ample o check if he id h i nega i e and di pla a me age.

DECLARE

l_width NUMBER(5) := -4;

l_length NUMBER(5) := -3;

BEGIN

IF (l_width = l_length) THEN

DBMS_OUTPUT.PUT_LINE('This is a square.');

ELSIF (l_width < 0) THEN

DBMS_OUTPUT.PUT_LINE('The width is negative.');

ELSE

DBMS_OUTPUT.PUT_LINE('This is a rectangle.');

.Da aba eS a .c m
PL/SQL T ial

END IF;

END;

The check of l_ id h < 0 ill e n a al e of e if he l_ id h i nega i e, and he me age belo ill


be di pla ed. Thi code ill onl be n if he id h and leng h a e no eq al.

The o p i :

Statement processed.

The width is negative.

Yo can e he ELSIF ke o d o add e a condi ion o o IF a emen .

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

l_width NUMBER(5) := -4;

l_length NUMBER(5) := -3;

BEGIN

IF (l_width = l_length) THEN

DBMS_OUTPUT.PUT_LINE('This is a square.');

ELSIF (l_width < 0) THEN

DBMS_OUTPUT.PUT_LINE('The width is negative.');

ELSE

DBMS_OUTPUT.PUT_LINE('This is a rectangle.');

END IF;

END;

Statement processed.

This is a square.

The o p a i i a q a e. Thi i beca e he fi IF a emen an, fo nd ha he al e a e


eq al, di pla ed he me age, and hen ended he IF a emen . If one condi ion i e, he e a e
kipped: he a en' n. Thi i an impo an poin o keep in mind.

Thi co ld be a p oblem in o applica ion. If o o ld p efe o di pla a me age abo he n mbe


being nega i e a he han i being a q a e, o can mo e o condi ion a o nd, and place he
nega i e check abo e he q a e check:

DECLARE

l_width NUMBER(5) := -4;

.Da aba eS a .c m
PL/SQL T ial

l_length NUMBER(5) := -4;

BEGIN

IF (l_width < 0) THEN

DBMS_OUTPUT.PUT_LINE('The width is negative.');

ELSIF (l_width = l_length) THEN

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.

The o p of hi code i ho n belo :

Statement processed.

The width is negative.

We can ee he o p make mo e en e no . The al e a e eq al, b beca e he id h i nega i e,


i di pla he nega i e me age.

M l iple C i e ia In A Condi ion

The e a ano he i e in o code abo e. We ha e checked he id h o ee if i i nega i e, b


ha if he id h i po i i e and he leng h i nega i e?

DECLARE

l_width NUMBER(5) := 6;

l_length NUMBER(5) := -4;

BEGIN

IF (l_width < 0) THEN

DBMS_OUTPUT.PUT_LINE('The width is negative.');

ELSIF (l_width = l_length) THEN

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;

Thi code ho he follo ing o p :

Statement processed.

This is a rectangle.

We don' an he me age o a i i a ec angle. We o ld a he a me age o a ha one of he


n mbe i nega i e.

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.

Fo e ample, e co ld check if ei he he leng h o id h i nega i e, and if o, di pla a me age


a ing ha one of he al e i nega i e. O code o ld look like hi :

DECLARE

l_width NUMBER(5) := 6;

l_length NUMBER(5) := -4;

BEGIN

IF (l_width < 0 OR l_length < 0) THEN

DBMS_OUTPUT.PUT_LINE('The width or length is negative.');

ELSIF (l_width = l_length) THEN

DBMS_OUTPUT.PUT_LINE('This is a square.');

ELSE

DBMS_OUTPUT.PUT_LINE('This is a rectangle.');

END IF;

END;

No ice ha o fi IF a emen incl de hi code:

l_width < 0 OR l_length < 0

The o condi ion ha e been epa a ed b he OR ke o d. Thi mean ha if ei he he id h < 0 o


he leng h < 0 hen he IF a emen ill e n e, and he code nde nea h ill n. Thi ill mean
ha o e ample ho ld ho he igh me age:

Statement processed.

The width or length is negative.

Thi ill handle i a ion he e one of he al e i nega i e and he o he i po i i e.

.Da aba eS a .c m
PL/SQL T ial

Yo can al o e he AND ke o d o check ha bo h condi ion a e e. Fo e ample, le ' a o


an ed o di pla a epa a e me age fo "big q a e " and a big q a e i he e he leng h i g ea e
han 50 and he leng h and id h a e he ame. Yo code o ld look like hi :

DECLARE

l_width NUMBER(5) := 55;

l_length NUMBER(5) := 55;

BEGIN

IF (l_width < 0 OR l_length < 0) THEN

DBMS_OUTPUT.PUT_LINE('The width or length is negative.');

ELSIF (l_width = l_length AND l_length > 50 ) THEN

DBMS_OUTPUT.PUT_LINE('This is a big square.');

ELSIF (l_width = l_length) THEN

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.

This is a big square.

Thi code ho ha he pecified al e make a big q a e.

Re e ing a Condi ion

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

l_width NUMBER(5) := -3;

.Da aba eS a .c m
PL/SQL T ial

l_length NUMBER(5) := -2;

BEGIN

IF NOT (l_width > 0 AND l_length > 0) THEN

DBMS_OUTPUT.PUT_LINE('The width or length is negative.');

ELSIF (l_width = l_length AND l_length > 50 ) THEN

DBMS_OUTPUT.PUT_LINE('This is a big square.');

ELSIF (l_width = l_length) THEN

DBMS_OUTPUT.PUT_LINE('This is a square.');

ELSE

DBMS_OUTPUT.PUT_LINE('This is a rectangle.');

END IF;

END;

The changed line of code i hi one:

IF NOT (l_width > 0 AND l_length > 0) THEN

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.

Wh did e al o change he OR o AND? Beca e of ho he o k.

We co ld ha e lef i like hi :

IF NOT (l_width > 0 OR l_length > 0) THEN

If e did, hen i ill onl e n TRUE if bo h of he al e a e fal e. I can be e plained b hi able:

l_ id h l_leng h Leng h > 0 Wid h > 0 U ing OR U ing AND

-3 -2 FALSE FALSE FALSE FALSE

4 -2 TRUE FALSE TRUE FALSE

-3 5 FALSE TRUE TRUE FALSE

4 5 TRUE TRUE TRUE TRUE

The onl i a ion he e bo h of he n mbe a e po i i e i he e AND e n e. If e e OR,


he a emen e n TRUE if ei he of he n mbe a e po i i e. Thi can e l in he ong me age
being ho n in o code.

.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 .

PL/SQL allo fo IF a emen o be ne ed in ide o he IF a emen , if ha ' ome hing o need


o do o implemen he logic o an .

The code o ld look like hi :

IF (condition) THEN

IF (condition) THEN

our_code;

ELSE

more_code;

END IF;

ELSIF (condition2) THEN

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.

PL/SQL ppo a la ge n mbe of ne ed IF a emen , o o can ne a man a o need.


Ho e e , if o a ge ing con ide ing he ma im m n mbe of ne ing hile o ' e p og amming,
o p obabl need o e i e o code. Ne ing mo e han 4 o 5 le el deep i all no he be
a o c e o code.

Le ' ee an e ample of a ne ed IF a emen . We'll adj o ea lie code o i e a me age ha le


kno hich of he al e i nega i e.

DECLARE

l_width NUMBER(5) := -3;

l_length NUMBER(5) := -2;

BEGIN

IF (l_width < 0 OR l_length < 0) THEN

IF (l_width < 0) THEN

DBMS_OUTPUT.PUT_LINE('The width is negative.');

END IF;

.Da aba eS a .c m
PL/SQL T ial

IF (l_length < 0) THEN

DBMS_OUTPUT.PUT_LINE('The length is negative.');

END IF;

ELSIF (l_width = l_length AND l_length > 50 ) THEN

DBMS_OUTPUT.PUT_LINE('This is a big square.');

ELSIF (l_width = l_length) THEN

DBMS_OUTPUT.PUT_LINE('This is a square.');

ELSE

DBMS_OUTPUT.PUT_LINE('This is a rectangle.');

END IF;

END;

Thi code ha ome ne ed IF a emen in ide he IF a emen ha check fo he id h o leng h


being le han 0.

Thi ho he follo ing o p :

Statement processed.

The width is negative.

The length is negative.

T o line of o p ha e been i en, beca e bo h of he ne ed IF a emen a e e. Thi ho


ho o can add an IF a emen in ide ano he IF a emen .

The CASE S a emen

IF a emen a e po e f l. The le o check fo diffe en condi ion and n diffe en code. Yo


p og am migh ge o a poin he e he e a e e e al IF and ELSIF a emen . If o, i can a o look
a li le me .

Yo migh be onde ing, i he e a be e a o do hi ?

Ye , he e i . I ' called a CASE a emen .

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 .

The CASE a emen look like hi :

CASE condition

WHEN value THEN code;

.Da aba eS a .c m
PL/SQL T ial

WHEN value THEN code;

ELSE default_code;

END CASE;

I look and ope a e he ame a a CASE a emen in eg la SQL.

The e a e a fe hing in hi CASE a emen :

● A condi ion: hi i he condi ion ha i checked.

● WHEN al e: hi define he al e of he condi ion ha i ed in he follo ing code.

● THEN code: hi code i n if he al e i eq al o he condi ion.

● ELSE defa l _code: hi code i n if none of he pecified al e ma ch he condi ion.

Le ' ee an e ample. Le ' a ha e an ed o ho pecific me age if he leng h i one of a fe


diffe en al e .

DECLARE

l_width NUMBER(5) := 5;

l_length NUMBER(5) := 10;

BEGIN

CASE l_length

WHEN 10 THEN

DBMS_OUTPUT.PUT_LINE('The length is ten.');

WHEN 20 THEN

DBMS_OUTPUT.PUT_LINE('The length is twent .');

WHEN 30 THEN

DBMS_OUTPUT.PUT_LINE('The length is thirt .');

ELSE

DBMS_OUTPUT.PUT_LINE('The length is another value.');

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

The length is ten.

The o p ho he me age "The leng h i en". If e change he leng h o 30, hi i ha e ee.

Statement processed.

The length is thirt .

If he leng h i no eq al o an of he al e in he CASE a emen , e ee he o he me age.

DECLARE

l_width NUMBER(5) := 5;

l_length NUMBER(5) := 10;

BEGIN

CASE l_length

WHEN 10 THEN

DBMS_OUTPUT.PUT_LINE('The length is ten.');

WHEN 20 THEN

DBMS_OUTPUT.PUT_LINE('The length is twent .');

WHEN 30 THEN

DBMS_OUTPUT.PUT_LINE('The length is thirt .');

ELSE

DBMS_OUTPUT.PUT_LINE('The length is another value.');

END CASE;

END;

Statement processed.

The length is another value.

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

Ano he ef l fea e of PL/SQL i a loop.

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 .

The e a e e e al a o i e loop in PL/SQL, hich e ill e plain in hi g ide.

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

● END LOOP o define he end of he code ha ' n a pa of he loop

● EXIT o op nning he loop

The code o ld look ome hing like hi :

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 .

If an EXIT a emen i eached, he loop e i , and an code af e he loop i hen n.

Le ' ee an e ample, he e e an o di pla an o p fi e ime on he c een.

O code o ld look like hi :

BEGIN

LOOP

DBMS_OUTPUT.PUT_LINE('A message here.');

END LOOP;

END;

.Da aba eS a .c m
PL/SQL T ial

If e n hi code, i ill keep nning i ho opping nle o fo ce i o op in o IDE (o


e e o e ion in Li eSQL).

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.

So ho o e op hi loop f om nning fo e e ? We need o ell i o e i a ome poin .

BEGIN

LOOP

DBMS_OUTPUT.PUT_LINE('A message here.');

IF (condition) THEN

EXIT;

END IF;

END LOOP;

END;

B ha ' o condi ion? We an o n he loop and di pla he me age fi e ime , o e need o


do o hing :

● Keep ack of ho man ime he loop ha n

● Check if he loop ha n fi e ime each ime i n

We can do this using a variable:

DECLARE

l_loop_counter NUMBER(3) := 0;

BEGIN

LOOP

DBMS_OUTPUT.PUT_LINE('A message here.');

IF (condition) THEN

EXIT;

END IF;

END LOOP;

END;

We ha e decla ed he a iable l_loop_co n e and a igned i a al e of 0, hich indica e he n mbe


of ime he loop ha been n. We no need o inc ea e he al e b 1 each ime e n he loop.

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;

DBMS_OUTPUT.PUT_LINE('A message here.');

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;

DBMS_OUTPUT.PUT_LINE('A message here.');

IF (l_loop_counter = 5) THEN

EXIT;

END IF;

END LOOP;

END;

Thi code no a he loop ill e i hen he l_loop_co n e al e eq al 5. Le ' n hi code:

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

Yo can change he al e in ide he condi ion f om 5 o 10 o ano he n mbe o change he n mbe


of ime he loop i n.

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.

Wha if o an ed o ho he n mbe of he loop in each me age? Yo can do ha ing


conca ena ion hich e lea ned abo ea lie . Yo can conca ena e he loop co n e a iable o he
me age:

DECLARE

l_loop_counter NUMBER(3) := 0;

BEGIN

LOOP

l_loop_counter := l_loop_counter + 1;

DBMS_OUTPUT.PUT_LINE('A message here: ' l_loop_counter);

IF (l_loop_counter = 5) THEN

EXIT;

END IF;

END LOOP;

END;

Thi code ho he loop co n e af e he me age:

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

U ing diffe en fea e of PL/SQL mean o can c ea e he p og am o eall need.

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 .

The n a of a FOR loop look like hi :

FOR counter IN start_value .. end_value LOOP

our_code

END LOOP;

Thi incl de a fe hing :

● The FOR ke o d a he loop

● The co n e a iable i he a iable ha i ed a an co n e fo he loop. I i


inc emen ed/inc ea ed b 1 each ime he loop i n.

● The a _ al e i he al e ha he co n e i ini iall e o.

● The end_ al e i he al e ha he co n e end on. When he co n e al e i g ea e han


he end_ al e, he loop e i and he code af e he loop i n.

An e ample of he PL/SQL FOR loop i ho n he e.

DECLARE

l_loop_counter NUMBER(3);

BEGIN

FOR l_loop_counter IN 1 .. 5 LOOP

DBMS_OUTPUT.PUT_LINE('Loop number: ' l_loop_counter);

END LOOP;

END;

Thi code i m ch ho e . The e i no need fo an IF a emen o check if he co n e i ill in ange.


The e i no need fo a epa a e line o inc ea e he al e of he loop co n e , a i ' done a pa of he
FOR loop.

Al o, no ice he n a of he a and end al e:

.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

We can ee he o p i imila , and he code i m ch ho e . FOR loop a e g ea in hi a : he


incl de a lo of he pa of a no mal LOOP in he n a , hich mean le code.

Yo can change he a and ending al e of he loop co n e o ha e e n mbe o an . B


he inc emen on each loop can onl go p o do n b 1:

DECLARE

l_loop_counter NUMBER(3);

BEGIN

FOR l_loop_counter IN 12 .. 20 LOOP

DBMS_OUTPUT.PUT_LINE('Loop number: ' l_loop_counter);

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

A o can ee, he FOR loop i e ef l. I gene all p efe ing i o he eg la LOOP na .

The While Loop

Ano he pe of loop offe ed in PL/SQL i he WHILE loop.

Wha i he WHILE loop?

I ' a pe of loop ha n n il he pecified condi ion i me . I ' imila o he ba ic LOOP b


incl de a condi ion hen o define i :

WHILE (condition) LOOP

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.

Fo e ample, hi code ill ca e an infini e loop.

DECLARE

l_loop_counter NUMBER(3);

BEGIN

WHILE (l_loop_counter < 5) LOOP

DBMS_OUTPUT.PUT_LINE('Loop number: ' l_loop_counter);

END LOOP;

END;

Thi code ill ca e an infini e loop beca e he e i no code ha inc ea e he l_loop_co n e o ha


ini iali e i i h a al e. We need o add hi code man all .

DECLARE

l_loop_counter NUMBER(3) := 0;

BEGIN

WHILE (l_loop_counter < 5) LOOP

DBMS_OUTPUT.PUT_LINE('Loop number: ' l_loop_counter);

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

The o p ho 5 o a e pec ed. The al e a e 0 o 4 beca e he loop co n e a a e o


and keep going n il i i no le han 5.

Diffe ence Be een Loop T pe

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:

C i e ia Ba ic LOOP FOR WHILE

Incl de he co n e defini ion No Ye No

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

Wha i he ke o d ed a pa of an IF a emen ha n code if none of he p o ided condi ion


a e me ?

● ELSE

● OTHERWISE

● FINAL

● END

Q e ion 2:

Wha doe he FOR a emen do?

● Ini iali e a a iable

● Check if a condi ion i e o fal e, and n he code in ide one ime if i i e

● Sa a loop and n he code in ide man ime n il he c i e ia i fal e

● Se p he da a eq i ed o end an email

Q e ion 3:

Which of he follo ing piece of code ill co ec l check ha o condi ion a e e in an IF


a emen ?

● IF (l_inp > 10) (l_inp < 20) THEN

● IF (l_inp > 10 & l_inp < 20) THEN

● IF (l_inp > 10 < 20) THEN

● IF (l_inp > 10 AND l_inp < 20) THEN

Q e ion 4:

Wha i ong i h hi code?

DECLARE

l_loop_counter NUMBER(3) := 8;

BEGIN

WHILE (l_loop_counter < 5) LOOP

DBMS_OUTPUT.PUT_LINE('Loop number: ' l_loop_counter);

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.

● No hing, i ill n cce f ll and ho fi e line of o p .

● I ill nb ca e an infini e loop.

● I ill n and ho eigh line of o p .

.Da aba eS a .c m
PL/SQL T ial

Chapter 4: Proced res, F nctions, and E ceptions


I hi cha e , 'll lea :

● 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!

Wha i a PL/SQL P ced e?

A PL/SQL ced e, ed ced e, i a e f c de ed he da aba e a d ha a ecific


ame. Thi ced e ca be b calli g i i he c de i g hi ame, a d he c de i ide he
ced e ill a d e f m he ac i i ide.

Wh c ea e ed ced e ?

● I ' he e m f PL/SQL c de ill g , a he ha i i g he amed c de like e


ha e d e fa .

● I all f he c de be e ed b calli g i f m he c de

● I all f a i e face API he da aba e.

Ea lie i hi g ide I me i ed e f he be efi f PL/SQL a ide a c mm i e face


he da aba e. P ced e le d ha .

F e am le, a he ha el i g e e a lica i de el e i g i e a INSERT


a eme ha k , ca c ea e a ced e ha acce a fe a ame e a d a INSERT
a eme i h hem. Thi mea he INSERT a eme a ec i e a d he de el e k
ha he eed ide.

Wha i a PL/SQL F ci ?

A PL/SQL f c i i a amed iece f c de he da aba e ha le ide a ame e , e f m


a calc la i , a d e a e l . The ca be ed i PL/SQL i eg la SQL. PL/SQL f c i a e
imila ced e b ha e me diffe e ce .

Wha ' he Diffe e ce Be ee a PL/SQL P ced e a d F ci ?

The mai diffe e ce be ee a PL/SQL ced e a d a PL/SQL f ci a e:

● F ci m e a al e. P ced e d ' e al e b ca e OUT a ame e .

.Da aba eS a .c m
PL/SQL T ial

● F ci ca be called f m eg la SQL, b ced e ca .

Th e a e he mai diffe e ce . P ced e a d f ci a e fe ed f diffe e hi g :

● Pe f mi g calc la i a d e i g a al e? U e a f ci .

● Pe f mi g e a d i e i g, da i g, dele i g da aba e ec d ? U e a ced e.

● Need call he c de f m SQL? U e a f ci .

Le ' ake a l ka h ca c ea e a ced e a d a f ci .

H C ea e a PL/SQL P ced e

A PL/SQL ced e i c ea ed i h he CREATE PROCEDURE a eme . The a f he


a eme l k like hi :

CREATE [OR REPLACE] PROCEDURE ced e_ ame

[ ( a ame e _ ame [ IN OUT IN OUT ] a ame e _ e [, ...] ) ]

IS AS

BEGIN

ced e_b d

END ced e_ ame;

The e a e a fe hi g ice he e:

● The ced e_ ame i he ame f he ced e c ea e.

● The OR REPLACE ke di i al. If i cl de i , i mea ha he hi


a eme i ill e lace he ced e i h he ame ame. If d ' i cl de i a d a
ced e i h hi ame al ead e i , 'll ge a e .

O e m e a ame e ca be ided:

● Pa ame e _ ame i he ame f he a ame e , hich i ed i ced e c de

● A a ame e ca be a IN a ame e ( al e i ided he ced e e), a OUT


a ame e ( al e i de e mi ed b he ced e a d e ed he c de ha ha called i ),
IN OUT (c mbi a i f IN a d OUT).

● A a ame e ha a a ame e _ e hich i a SQL da a e, ch a NUMBER.

● F he a ame e ca be added a d e a a ed b c mma .

Af e defi e he a ame e :

● S ecif ei he IS AS a he ced e c de.

● BEGIN i ecified j like e ha e lea ed fa .

● Y add he c de f ced e, a d fi i h i h END ced e_ ame.

.Da aba eS a .c m
PL/SQL T ial

E am le PL/SQL P ced e

Le ' ake a l k a a e am le. We'll e ea lie c de ha check al e f a a e ec a gle:

DECLARE

l_ id h NUMBER(5) := 18;

l_le g h NUMBER(5) := 15;

BEGIN

IF (l_ id h < 0 OR l_le g h < 0) THEN

DBMS_OUTPUT.PUT_LINE('The id h le g h i ega i e.');

ELSIF (l_ id h = l_le g h AND l_le g h > 50 ) THEN

DBMS_OUTPUT.PUT_LINE('Thi i a big a e.');

ELSIF (l_ id h = l_le g h) THEN

DBMS_OUTPUT.PUT_LINE('Thi i a a e.');

ELSE

DBMS_OUTPUT.PUT_LINE('Thi i a ec a gle.');

END IF;

END;

Thi c de i a ced e a f c i , a i ha ame. Thi c de i called a "a m bl ck",


beca e i ha ame (i ' a m ) a d i a bl ck f c de. S , if a e efe a a m
bl ck, i mea a ec i f PL/SQL c de ha i af c i ced e.

T c e hi a ced e, e eed gi e i a ame. Le ' call i "check_ ec a gle". Name f


f ci a d ced e i PL/SQL m mee he f ll i g c i e ia:

● The ma im m le g h i 30 cha ac e

● The fi cha ac e m be a le e

● The cha ac e af e he fi cha ac e ca be le e , mbe , d lla ig $, mbe ig #,


a de c e _.

Al , PL/SQL ame a e ca e-i e i i e. Thi mea he f ll i g ame a e all e i ale :

● check_ ec a gle

● CHECK_RECTANGLE

● Check_Rec a gle

.Da aba eS a .c m
PL/SQL T ial

I' ha ca e ch ef PL/SQL ame , a i c me d c di g


a da d . I hi g ide, I'll be i g all l e ca e f m ced e a d f c i ame .

Le ' a check_ ec a gle ced e:

CREATE OR REPLACE PROCEDURE check_ ec a gle

I ha e added he OR REPLACE ke d he e ha ca he ame a eme e a d e


agai if a make a cha ge . Y d ' eed d he ced e e a a el .

We he ha e ei he he IS AS ke d. I'll e he AS beca e i ' a e al efe e ce. The e i


diffe e ce be ee he e ke d .

CREATE OR REPLACE PROCEDURE check_ ec a gle

AS

The e ca add i c de. We ca c a d a e he c de f m ea lie ( he a m bl ck) a d


add i he e, a d add he ced e_ ame he END ke d.

CREATE OR REPLACE PROCEDURE check_ ec a gle

AS

DECLARE

l_ id h NUMBER(5) := 18;

l_le g h NUMBER(5) := 15;

BEGIN

IF (l_ id h < 0 OR l_le g h < 0) THEN

DBMS_OUTPUT.PUT_LINE('The id h le g h i ega i e.');

ELSIF (l_ id h = l_le g h AND l_le g h > 50 ) THEN

DBMS_OUTPUT.PUT_LINE('Thi i a big a e.');

ELSIF (l_ id h = l_le g h) THEN

DBMS_OUTPUT.PUT_LINE('Thi i a a e.');

ELSE

DBMS_OUTPUT.PUT_LINE('Thi i a ec a gle.');

END IF;

END check_ ec a gle;

If e hi c de, e ge a e me age:

E : PROCEDURE CHECK_RECTANGLE Li e/C l: 3/1 PLS-00103: E c e ed


he mb l "DECLARE" he e ec i g e f he f ll i g: begi f c i
agma ced e b e e <a ide ifie > <a d ble- ed

.Da aba eS a .c m
PL/SQL T ial

delimi ed-ide ifie > c e c dele e e i i e e al


la g age

Thi e a ea beca e e ha e a DECLARE a eme i c de. Beca e e' e i i g a


ced e, e d ' eed he DECLARE ke d. The a iable ca g j af e he AS IS ke d
a d bef e he BEGIN. Sim l em e he DECLARE ke d:

CREATE OR REPLACE PROCEDURE check_ ec a gle

AS

l_ id h NUMBER(5) := 18;

l_le g h NUMBER(5) := 15;

BEGIN

IF (l_ id h < 0 OR l_le g h < 0) THEN

DBMS_OUTPUT.PUT_LINE('The id h le g h i ega i e.');

ELSIF (l_ id h = l_le g h AND l_le g h > 50 ) THEN

DBMS_OUTPUT.PUT_LINE('Thi i a big a e.');

ELSIF (l_ id h = l_le g h) THEN

DBMS_OUTPUT.PUT_LINE('Thi i a a e.');

ELSE

DBMS_OUTPUT.PUT_LINE('Thi i a ec a gle.');

END IF;

END check_ ec a gle;

Y 'll ge hi :

P ced e c ea ed.

Whe c ea i g a ced e like hi , he ced e i l c ea ed a d . Y 'll l ee he


"P ced e c ea ed" me age, a f he i ide he ced e. Y 'll eed call he
ced e d ha .

T call a PL/SQL ed ced e, ca d e f h ee hi g :

● CALL ced e_ ame;

● EXEC ced e_ ame;

● BEGIN ced e_ ame END;

Y c de a d ill l k like hi :

CALL check_ ec a gle;

.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:

EXEC check_ ec a gle;

S a eme ce ed.

Thi i a ec a gle.

O ca e a BEGIN END bl ck:

BEGIN

check_ ec a gle;

END;

S a eme ce ed.

Thi i a ec a gle.

I ' ea a ced e af e i ' bee c ea ed.

U i gI Pa ame e i h PL/SQL P ced e

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.

Wha if a ed hi ced e i h diffe e al e ?

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

Thi i a l f e j ee he ced e i h diffe e al e .

A he a d hi i e a ame e . Pa ame e le ecif he al e ed f he


a iable he he ced e, hich a e he ed i he calc la i . I ' m ch be e d i
hi a ha ec m ile he ced e.

I hi e am le, e'll lea h ide he le g h a d id h al e a a ame e .

.Da aba eS a .c m
PL/SQL T ial

O c de l k like hi fa :

CREATE OR REPLACE PROCEDURE check_ ec a gle

AS

l_ id h NUMBER(5) := 18;

l_le g h NUMBER(5) := 15;

BEGIN

IF (l_ id h < 0 OR l_le g h < 0) THEN

DBMS_OUTPUT.PUT_LINE('The id h le g h i ega i e.');

ELSIF (l_ id h = l_le g h AND l_le g h > 50 ) THEN

DBMS_OUTPUT.PUT_LINE('Thi i a big a e.');

ELSIF (l_ id h = l_le g h) THEN

DBMS_OUTPUT.PUT_LINE('Thi i a a e.');

ELSE

DBMS_OUTPUT.PUT_LINE('Thi i a ec a gle.');

END IF;

END check_ ec a gle;

T add a ame e , e add b acke af e he ced e_ ame decla a i he fi li e:

CREATE OR REPLACE PROCEDURE check_ ec a gle ()

AS

l_ id h NUMBER(5) := 18;

l_le g h NUMBER(5) := 15;

BEGIN

IF (l_ id h < 0 OR l_le g h < 0) THEN

DBMS_OUTPUT.PUT_LINE('The id h le g h i ega i e.');

ELSIF (l_ id h = l_le g h AND l_le g h > 50 ) THEN

DBMS_OUTPUT.PUT_LINE('Thi i a big a e.');

ELSIF (l_ id h = l_le g h) THEN

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;

END check_ ec a gle;

I ide he b acke , e add a ame e : e f l_ id h, a d e f l_le g h. We defi e he e a


IN a ame e , beca e he a e bei g ided he ced e b he c de. We al ecif hem
a a NUMBER da a e.

CREATE OR REPLACE PROCEDURE check_ ec a gle (

l_ id h IN NUMBER, l_le g h IN NUMBER

AS

l_ id h NUMBER(5) := 18;

l_le g h NUMBER(5) := 15;

BEGIN

IF (l_ id h < 0 OR l_le g h < 0) THEN

DBMS_OUTPUT.PUT_LINE('The id h le g h i ega i e.');

ELSIF (l_ id h = l_le g h AND l_le g h > 50 ) THEN

DBMS_OUTPUT.PUT_LINE('Thi i a big a e.');

ELSIF (l_ id h = l_le g h) THEN

DBMS_OUTPUT.PUT_LINE('Thi i a a e.');

ELSE

DBMS_OUTPUT.PUT_LINE('Thi i a ec a gle.');

END IF;

END check_ ec a gle;

I' e added he a ame e a e a a e li e make i m e eadable, b i' h d


hi .

N e eed em e hem f m he decla a i ec i . The a e al ead decla ed i he


a ame e .

CREATE OR REPLACE PROCEDURE check_ ec a gle (

l_ id h IN NUMBER, l_le g h IN NUMBER

AS

BEGIN

IF (l_ id h < 0 OR l_le g h < 0) THEN

.Da aba eS a .c m
PL/SQL T ial

DBMS_OUTPUT.PUT_LINE('The id h le g h i ega i e.');

ELSIF (l_ id h = l_le g h AND l_le g h > 50 ) THEN

DBMS_OUTPUT.PUT_LINE('Thi i a big a e.');

ELSIF (l_ id h = l_le g h) THEN

DBMS_OUTPUT.PUT_LINE('Thi i a a e.');

ELSE

DBMS_OUTPUT.PUT_LINE('Thi i a ec a gle.');

END IF;

END check_ ec a gle;

Le ' hi he da aba e.

P ced e c ea ed.

The ced e i c ea ed. Le ' hi ced e a d e a ame e . F hi e am le I'll e


he CALL ke d b i ill k i h a me h d e' e ee fa .

Le ' i i h he igi al al e f 18 a d 15. T e a ame e i a call a ced e, ecif


hem i ide b acke af e he ced e ame, e a a ed b c mma , like hi :

CALL check_ ec a gle(18, 15);

The f m hi a eme i :

S a eme ce ed.

Thi i a ec a gle.

Thi i called " i i al a i ", beca e ' e a i g a ame e i ha a e ge i g ce ed


ba ed hei i i i ide he b acke .

The he a d hi i called " amed ai ", he e ecif he a ame e ame a d he


al e he call i :

CALL check_ ec a gle(l_ id h=>18, l_le g h=>15);

Thi i d e b ecif i g he a ame e ame, a d he he al e, e a a ed b a => mb l a ig


he al e f he a ame e .

Thi h he f ll i g :

S a eme ce ed.

Thi i a ec a gle.

N ' e ee h he c de i h a ame e , le ' a fe diffe e a ia i f he


ced e eall ee h ef l a ame e a e:

CALL check_ ec a gle(18, 15);

CALL check_ ec a gle(20, 32);

.Da aba eS a .c m
PL/SQL T ial

CALL check_ ec a gle(80, 80);

CALL check_ ec a gle(-2, 12);

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.

Thi e am le h h ef l a ame e a e. Y ca im l cha ge he i al e ha e he


ced e agai i g he e e al e .

U i gO Pa ame e i h PL/SQL P ced e

We' e lea ed h ei a ame e ecif i ced e. Le ' lea h e


a ame e .

Wh ld e a ame e i PL/SQL c de? The mai ea i ca e he


f m he ced e el e he e i c de.

We'll da e ced e ea a ame e , a d he e ha i he c de.

He e' ced e a he m me :

CREATE OR REPLACE PROCEDURE check_ ec a gle (

l_ id h IN NUMBER, l_le g h IN NUMBER

AS

BEGIN

IF (l_ id h < 0 OR l_le g h < 0) THEN

DBMS_OUTPUT.PUT_LINE('The id h le g h i ega i e.');

ELSIF (l_ id h = l_le g h AND l_le g h > 50 ) THEN

DBMS_OUTPUT.PUT_LINE('Thi i a big a e.');

ELSIF (l_ id h = l_le g h) THEN

.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;

END check_ ec a gle;

Le ' a e a e he me age di la , i ead f di la i g i he c ee i g


PUT_LINE. Thi i he c de ha call hi ced e ca decide ha d i h i : ei he di la i
he c ee , add i a da aba e able, me hi g el e.

Fi , e add a OUT a ame e f he me age. Thi i he a iable e hi i c ea ed, a d i


ca be e ed he c de ha call i .

CREATE OR REPLACE PROCEDURE check_ ec a gle (

l_ id h IN NUMBER, l_le g h IN NUMBER, l_me age OUT VARCHAR2

AS

BEGIN

IF (l_ id h < 0 OR l_le g h < 0) THEN

DBMS_OUTPUT.PUT_LINE('The id h le g h i ega i e.');

ELSIF (l_ id h = l_le g h AND l_le g h > 50 ) THEN

DBMS_OUTPUT.PUT_LINE('Thi i a big a e.');

ELSIF (l_ id h = l_le g h) THEN

DBMS_OUTPUT.PUT_LINE('Thi i a a e.');

ELSE

DBMS_OUTPUT.PUT_LINE('Thi i a ec a gle.');

END IF;

END check_ ec a gle;

We ca he e hi a iable he me age e a h i ead f i g PUT_LINE:

CREATE OR REPLACE PROCEDURE check_ ec a gle (

l_ id h IN NUMBER, l_le g h IN NUMBER, l_me age OUT VARCHAR2

AS

BEGIN

IF (l_ id h < 0 OR l_le g h < 0) THEN

.Da aba eS a .c m
PL/SQL T ial

l_me age := 'The id h le g h i ega i e.';

ELSIF (l_ id h = l_le g h AND l_le g h > 50 ) THEN

l_me age := 'Thi i a big a e.';

ELSIF (l_ id h = l_le g h) THEN

l_me age := 'Thi i a a e.';

ELSE

l_me age := 'Thi i a ec a gle.';

END IF;

END check_ ec a gle;

If e hi c de, hi i he e ge :

P ced e c ea ed.

We ca he he me age i g he PL/SQL c de, i ei a da aba e i ead:

DECLARE

l_ _me age VARCHAR2(100);

BEGIN

check_ ec a gle(10, 5, l_ _me age);

DBMS_OUTPUT.PUT_LINE(l_ _me age);

END;

I hi c de, e ha e decla ed a e a iable f he me age. I he BEGIN bl ck, e he


check_ ec a gle f c i ih le g h a d id h a ame e . The hi d a ame e i he
l_ _me age a iable, hich i e i ide he check_ ec a gle ced e. We he hi
al e.

R i g hi c de h hi :

S a eme ce ed.

Thi i a ec a gle.

We c ld i e hi i a da aba e able i ead if e a ed, beca e he c de i fle ible.

CREATE TABLE me age_ (

me age_ al VARCHAR2(100)

);

We ca he hi c de, hich i e i he able i ead f di la i he c ee :

DECLARE

.Da aba eS a .c m
PL/SQL T ial

l_ _me age VARCHAR2(100);

BEGIN

check_ ec a gle(10, 5, l_ _me age);

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.

SELECT * FROM me age_ ;

MESSAGE_VAL

Thi i a ec a gle.

S , i g a di a ame e ca be e ef l i PL/SQL ced e a he all d


ha eed i h he al e i c de.

H C ea e a PL/SQL F ci

The he e f c de bjec ca c ea e i h PL/SQL i a f ci .

A PL/SQL f ci me c de a d e a al e. I ca be ed i eg la SQL a ell a PL/SQL.

C ea i g a f ci i imila c ea i g a ced e:

CREATE [OR REPLACE] FUNCTION f c i _ ame

[ ( a ame e _ ame [ IN OUT IN OUT ] a ame e _ 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:

● The f ci _ ame i he ame f he f ci c ea e.

● The OR REPLACE ke di i al. If i cl de i , i mea ha he hi


a eme i ill e lace he f c i i h he ame ame. If d ' i cl de i a d a f ci
i h hi ame al ead e i , 'll ge a e .

.Da aba eS a .c m
PL/SQL T ial

O e m e a ame e ca be ided:

● Pa ame e _ ame i he ame f he a ame e , hich i ed i f ci c de

● A a ame e ca be a IN a ame e ( al e i ided he f ci e), a OUT


a ame e ( al e i de e mi ed b he f c i a d e ed he c de ha ha called i ),
IN OUT (c mbi a i f IN a d OUT).

● A a ame e ha a a ame e _ e hich i a SQL da a e, ch a NUMBER.

● F he a ame e ca be added a d e a a ed b c mma .

Af e defi e he a ame e :

● Add he RETURN ke d a d he he da a e f he e al e. Thi le he da aba e


k he e f da a ha ill be e ed f m he f c i .

● S ecif ei he IS AS a he f ci c de.

● BEGIN i ecified j like e ha e lea ed fa .

● Y add he c de f f ci , a d fi i h i h END f ci _ ame.

E am le PL/SQL F ci

Le ' i e a e am le PL/SQL f c i . S fa e' e bee ki g i h c de ha de e mi e ha


ki d f ha e i c ea ed he a le g h a d id h i ided. Le ' i eaf c i ha calc la e he
a ea f a ha e i h he le g h a d id h ided.

O f ci ill l k like hi :

CREATE OR REPLACE FUNCTION ha e_a ea

(l_ id h IN NUMBER, l_le g h IN NUMBER)

RETURN NUMBER

AS

BEGIN

END;

We ha e he decla a i f he f c i , hich i cl de he ame f ha e_a ea. I al i cl de


a ame e , a d e a mbe .

B he f ci d e ' d a hi g.

Le ' ie me f ci c de.

CREATE OR REPLACE FUNCTION ha e_a ea

(l_ id h IN NUMBER, l_le g h IN NUMBER)

.Da aba eS a .c m
PL/SQL T ial

RETURN NUMBER

AS

BEGIN

RETURN l_ id h * l_le g h;

END;

We' e added e li e, hich calc la e he le g h * id h a d e i i g he RETURN ke d.


Thi mea ha a ime hi f c i i called, i e he al e f he le g h m l i lied b he
id h.

Le ' c ea e hi f ci . The h :

F c i c ea ed.

The f ci i c ea ed. We ca call he f ci f m PL/SQL, like hi :

BEGIN

DBMS_OUTPUT.PUT_LINE( ha e_a ea(5, 4));

END;

Thi c de h he f ll i g :

S a eme ce ed.

20

Beca e hi c de i a f ci , e ca call i f m SQL a ell:

SELECT ha e_a ea(5, 4)

FROM d al;

SHAPE_AREA(5,4)

20

C ea i g a f ci i j like c ea i g a ced e, e ce he RETURN a eme i eeded.

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

The g d e i PL/SQL i ha ca i e c de k i h he e e ce i . Thi i called


"e ce i ha dli g", a d i ' he e c de ca ee ha a e ha ha e ed a d ake a diffe e
ac i . Wi h e ce i ha dli g, e a e e ed he g am ha call i a d di la ed
ei he i IDE i he a lica i .

S a f E ce i Ha dli g i PL/SQL

W i i g c de ha dle e ce i i PL/SQL l k like hi :

BEGIN

e ec able_c de;

EXCEPTION

WHEN e ce i _ e THEN

e ce i _c de;

WHEN OTHERS THEN

e ce i _c de;

END;

The BEGIN ec i i he ame: hi i he e e ec able c de g e .

AN EXCEPTION ec i i added af e e ec able c de, a he e d f c de bl ck, bef e he


END a eme . Thi EXCEPTION ec i c ai c de f ha dli g a e ce i ha cc .

Wi hi he EXCEPTION ec i i a e ie f WHEN THEN a eme . Each f he e a eme


ela e a ible e ce i ha ca be f d. Whe a e ce i i f d he i g c de,
i ' called " h i g a e ce i ". I'm e h i ' called " h i g", b ha ' j he
g ammi g e m f i .

Whe a e ce i i f d, he WHEN a eme a e checked. I he WHEN a eme ecif


he e f e ce i , like a IF a eme . If he e ha a f d ma che he ei WHEN
a eme , he c de de ea h i .

If he e d e ' ma ch a f WHEN a eme , ca ha e a WHEN OTHERS THEN


a eme , hich i hi i ai .

Le ' ake a l k a a e am le.

E am le E ce i C de i PL/SQL

We'll e a a ia i f ea lie c de ha calc la e he a ea f a ha e. I ead f i ga


ced e a f c i , e'll j ea a m PL/SQL bl ck.

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;

DBMS_OUTPUT.PUT_LINE('The a ea i : ' l_a ea);

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

I h he a ea i 20, beca e 5*4 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_le g h NUMBER := 400;

l_ id h NUMBER := 500;

l_a ea NUMBER(3);

BEGIN

l_a ea := l_le g h * l_ id h;

DBMS_OUTPUT.PUT_LINE('The a ea i : ' l_a ea);

END;

Wha ha e he e he c de?

We ge a e me age:

ORA-06502: PL/SQL: me ic al e e : mbe eci i la ge


ORA-06512: a li e 6 ORA-06512: a "SYS.DBMS_SQL", li e 1721

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_le g h NUMBER := 400;

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;

DBMS_OUTPUT.PUT_LINE('The a ea i : ' l_a ea);

EXCEPTION

WHEN VALUE_ERROR THEN

DBMS_OUTPUT.PUT_LINE('The e a a blem ecif i g he a ea. '


SQLERRM);

END;

We ha e added i he EXCEPTION ec i . We ha e al added i he WHEN a eme : WHEN


VALUE_ERROR. Thi ill ick a ORA-06502 e e ma e e ie ce i c de. The ea
ha VALUE_ERROR i ed i ead f he e c de i ha he ame i ea ide if a d ead.

Af e he WHEN a eme e ha e a PUT_LINE f c i call ha i e a me age, a i g he e a


a blem i h he a ea. We he c ca e a e me hi g called SQLERRM.

SQLERRM i a SQL f c i ha e he e me age f di he ece l -e ec ed c de. Thi


ill all ee he de ail f he e me age.

If e hi c de, e ge hi :

S a eme ce ed.

The e a a blem ecif i g he a ea. ORA-06502: PL/SQL: me ic


al e e : mbe eci i la ge

Thi ha bee i e a a f m PUT_LINE a he ha a e me age. I mea he


g am ill kee i ga d ca d m e i h hi me age, i ead f j i g he
g am.

Rai i g E ce i i PL/SQL

We' e ee ha ha e if e e f m a calc la i e a al e ha ' highe ha he ma im m


i e, d me hi g ha O acle d e e ec . Thi e a b il -i e ce i .

Wha if e fi d me hi g ha b i e le a i alid, b i ' OK i h he O acle


da aba e?

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_le g h NUMBER := -4;

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;

DBMS_OUTPUT.PUT_LINE('The a ea i : ' l_a ea);

EXCEPTION

WHEN VALUE_ERROR THEN

DBMS_OUTPUT.PUT_LINE('The e a a blem ecif i g he a ea. '


SQLERRM);

END;

The i :

S a eme ce ed.

The a ea i : -12

Thi h he a ea a -12, hich i a alid al e. We d ' a ha e ega i e a ea al e .

We ca a id hi b c ea i g ai i g e ce i .T d hi :

● Decla e a e a iable hich ha a e f EXCEPTION

● 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

T d hi i c de, e decla e a e a iable i h a e f EXCEPTION.

DECLARE

l_le g h NUMBER := -4;

l_ id h NUMBER := 3;

l_a ea NUMBER(3);

e _ ega i e_a ea EXCEPTION;

BEGIN

l_a ea := l_le g h * l_ id h;

DBMS_OUTPUT.PUT_LINE('The a ea i : ' l_a ea);

EXCEPTION

WHEN VALUE_ERROR THEN

DBMS_OUTPUT.PUT_LINE('The e a a blem ecif i g he a ea. '


SQLERRM);

END;

N , e' e c ea ed a e a iable called e _ ega i e_a ea. Thi i a EXCEPTION. We eed


check if he a ea i ega i e, a d if i i , ai e he e ce i .

.Da aba eS a .c m
PL/SQL T ial

DECLARE

l_le g h NUMBER := -4;

l_ id h NUMBER := 3;

l_a ea NUMBER(3);

e _ ega i e_a ea EXCEPTION;

BEGIN

l_a ea := l_le g h * l_ id h;

IF (l_a ea < 0) THEN

RAISE e _ ega i e_a ea;

END IF;

DBMS_OUTPUT.PUT_LINE('The a ea i : ' l_a ea);

EXCEPTION

WHEN VALUE_ERROR THEN

DBMS_OUTPUT.PUT_LINE('The e a a blem ecif i g he a ea. '


SQLERRM);

END;

Thi c de check if he a ea i le ha e . If i i , he he e ce i i ai ed i g he RAISE


e _ ega i e_a ea a eme .

Fi all , e eed add hi EXCEPTION ec i . If e j ai e he e ce i ih i i ga


WHEN a eme , hi i ha e ill ee:

U e -Defi ed E ce i ORA-06512: a li e 9 ORA-06512: a


"SYS.DBMS_SQL", li e 1721

The e -defi ed e ce i e me age mea e ai ed he e ce i b did hi g i h i .

O e c de ill l k like hi :

DECLARE

l_le g h NUMBER := -4;

l_ id h NUMBER := 3;

l_a ea NUMBER(3);

e _ ega i e_a ea EXCEPTION;

BEGIN

l_a ea := l_le g h * l_ id h;

IF (l_a ea < 0) THEN

.Da aba eS a .c m
PL/SQL T ial

RAISE e _ ega i e_a ea;

END IF;

DBMS_OUTPUT.PUT_LINE('The a ea i : ' l_a ea);

EXCEPTION

WHEN e _ ega i e_a ea THEN

DBMS_OUTPUT.PUT_LINE('The a ea i ega i e. Plea e c fi m he i


al e a e i i e.');

WHEN VALUE_ERROR THEN

DBMS_OUTPUT.PUT_LINE('The e a a blem ecif i g he a ea. '


SQLERRM);

END;

We ca hi c de.

S a eme ce ed.

The a ea i ega i e. Plea e c fi m he i al e a e i i e.

The me age h i ha e ha e e e ed i he EXCEPTION ec i .I a he a ea i ega i e,


hich i ha e a ed di la .

C cl i

P ced e a d f c i i PL/SQL a e bjec ha c ai PL/SQL c de f a a la e


age. The ha e e e al ad a age ch a he abili e e c de a d im lif
g ammi g. The e a e me diffe e ce be ee ced e a d f c 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

Which e f he e a eme i e ab he diffe e ce be ee a ced e a d a f ci ?

● The a e b h he ame.

● F ci m ha e a RETURN al e, b ced e d ' eed e.

● P ced e ca l ake IN a ame e a d OUT a ame e .

● 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

Wha d e he OR REPLACE ke dd a a f he CREATE PROCEDURE CREATE


FUNCTION a eme ?

● I e lace he e i i g bjec i h he e ha e defi ed i he a eme if i al ead


e i .

● N hi g, hi ke di alid.

● N hi g, i ' a alid ke db d e a l ced e f ci .

● 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?

● R he "CALL ced e_ ame" a eme .

● I' a ma icall he c ea e he ced e.

● R he "RUN ced e_ ame" a eme .

● 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

The o pes of c rsors

Inser ing, pda ing, and dele ing da a in ables sing PL/SQL

Selec ing da a from a able in o PL/SQL

Wha an arra is and ho o se one

Wha Is a C rsor in 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.

Whene er o r r n a DML s a emen (INSERT, UPDATE, DELETE, or SELECT), an implici c rsor is


crea ed:

For INSERT s a emen s, he c rsor con ains he da a ha is being inser ed.

For UPDATE or DELETE s a emen s, he c rsor iden ifies he ro s ha ill be affec ed

For SELECT s a emen s, he ro s ha are re rie ed can be s ored in an objec .

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 .

Le 's see an e ample of his.

E ample - Using a C rsor i h INSERT

Le 's see ha can be done i h an implici c rsor and an INSERT s a emen .

Firs , e'll need o crea e a able:

CREATE TABLE person (

.Da aba eS a .c m
PL/SQL T ial

fname VARCHAR2(50)

);

If o r n his in an SQL indo , he able ill be crea ed.

No le 's ri e some PL/SQL o inser da a in o his able.

BEGIN

INSERT INTO person (fname)

VALUES ('John');

DBMS_OUTPUT.PUT_LINE('To al n mber of ro s impac ed: '


sql%ro co n );

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 .

If e r n his code, e sho ld see his o p :

1 ro (s) inser ed.

To al n mber of ro s impac ed: 1

The o p sho s he n mber of impac ed ro s. We can do more i h his al e, s ch as s oring i in a


ariable:

DECLARE

l_ o al_ro s NUMBER(10);

BEGIN

INSERT INTO person (fname)

VALUES ('John');

l_ o al_ro s := sql%ro co n ;

DBMS_OUTPUT.PUT_LINE('To al n mber of ro s impac ed: '


l_ o al_ro s);

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

INSERT INTO person (fname)

.Da aba eS a .c m
PL/SQL T ial

VALUES ('John');

l_ o al_ro s := sql%ro co n ;

IF (l_ o al_ro s > 0) THEN

DBMS_OUTPUT.PUT_LINE('Ro s inser ed: ' l_ o al_ro s);

ELSE

DBMS_OUTPUT.PUT_LINE('No ro s inser ed.');

END IF;

END;

If o r n a SELECT s a emen on o r able, o sho ld see he da a in he able. Ass ming he


s a emen as onl r n once, his is ha o 'll see:

FNAME

John

E ample - Using a C rsor i h UPDATE

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

SET fname='S san'

WHERE fname = 'John';

DBMS_OUTPUT.PUT_LINE('To al n mber of ro s impac ed: '


sql%ro co n );

END;

If e r n his code, e'll ge his o p :

1 ro (s) pda ed.

To al n mber of ro s impac ed: 1

I sa s ha 1 ro is impac ed b o r pda e s a emen . The ro is also pda ed: ha UPDATE


s a emen is e ec ed. If e r n a SELECT q er on he able, e'll see he ne al e:

FNAME

S san

.Da aba eS a .c m
PL/SQL T ial

No , le 's r n o r earlier code and see ha happens:

1 ro (s) pda ed.

To al n mber of ro s impac ed: 0

I sa s 0 ro s are impac ed (e en ho gh he o p also sa s "1 ro (s) pda ed"). This is beca se he


WHERE cla se means he s a emen is looking for a ro of "John", b he al e in he ro is eq al o
"S san", so i is no pda ed.

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.

The %FOUND a rib e ill re rn r e if a leas one ro is impac ed b an INSERT, UPDATE, or


DELETE s a emen , o her ise i ill re rn false. The %NOTFOUND a rib e is he opposi e: i ill
re rn r e if no ro s are impac ed, and false if a leas one ro is impac ed.

We can change o r code o se he %FOUND a rib e:

BEGIN

UPDATE person

SET fname='S san'

WHERE fname = 'John';

IF (sql%fo nd) THEN

DBMS_OUTPUT.PUT_LINE('Ro s pda ed: ' sql%ro co n );

ELSE

DBMS_OUTPUT.PUT_LINE('Ro s no pda ed.');

END IF;

END;

This o p is sho n:

1 ro (s) pda ed.

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.

We can change o r UPDATE s a emen so ro s are fo nd:

BEGIN

UPDATE person

SET fname='Mark'

WHERE fname = 'S san';

.Da aba eS a .c m
PL/SQL T ial

IF (sql%fo nd) THEN

DBMS_OUTPUT.PUT_LINE('Ro s pda ed: ' sql%ro co n );

ELSE

DBMS_OUTPUT.PUT_LINE('Ro s no pda ed.');

END IF;

END;

1 ro (s) pda ed.

Ro s pda ed: 1

E ample - Using a C rsor i h DELETE

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

DELETE FROM person

WHERE fname = 'S san';

IF (sql%fo nd) THEN

DBMS_OUTPUT.PUT_LINE('Ro s pda ed: ' sql%ro co n );

ELSE

DBMS_OUTPUT.PUT_LINE('Ro s no pda ed.');

END IF;

END;

This o p sho s ha no ro s ere dele ed.

1 ro (s) dele ed.

Ro s no pda ed.

This is beca se no ro s ha e an fname al e of "S san". If e change i o "Mark" and r n he


s a emen again, he ro ill be dele ed.

BEGIN

DELETE FROM person

WHERE fname = 'Mark';

IF (sql%fo nd) THEN

.Da aba eS a .c m
PL/SQL T ial

DBMS_OUTPUT.PUT_LINE('Ro s pda ed: ' sql%ro co n );

ELSE

DBMS_OUTPUT.PUT_LINE('Ro s no pda ed.');

END IF;

END;

1 ro (s) dele ed.

Ro s pda ed: 1.

Selec ing Da a i h an Implici C rsor

Wha abo a SELECT q er i h an implici c rsor? Tha orks a li le differen l .

We can se a SELECT q er i h an implici c rsor. Ho e er, e need o se a ariable o s ore he


re rned al e. We can se SELECT INTO for his.

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 .

Ens re o r person able onl has one ro in i :

DELETE FROM person;

INSERT INTO person (fname) VALUES ('John');

SELECT * FROM person;

No , le 's ri e some PL/SQL code o selec his al e in o a ariable.

DECLARE

l_fname VARCHAR2(50);

BEGIN

SELECT fname

INTO l_fname

FROM person;

DBMS_OUTPUT.PUT_LINE('The name is ' l_fname);

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

The o p from his s a emen is:

S a emen processed.

The name is John

We can see he o p sa s "The name is John".

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.

Here's he code o inser ano her ro in o he able:

INSERT INTO person (fname) VALUES ('S san');

SELECT * FROM person;

FNAME

John

S san

No , le 's r n o r PL/SQL code o SELECT he al e from his col mn in o a ariable.

DECLARE

l_fname VARCHAR2(50);

BEGIN

SELECT fname

INTO l_fname

FROM person;

DBMS_OUTPUT.PUT_LINE('The name is ' l_fname);

END;

This is o r o p . The error message e ge is:

ORA-01422: e ac fe ch re rns more han req es ed n mber of ro s


ORA-06512: a line 4 ORA-06512: a "SYS.DBMS_SQL", line 1721

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.

Ho do e handle si a ions like his? We'll learn abo ha la er in his g ide.

For no , le 's look a e plici c rsors.

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.

Using an e plici c rsor in ol es se eral s eps:

1. Declaring he c rsor as a ariable in he DECLARE sec ion.

2. Opening he c rsor, hich alloca es memor for i .

3. Fe ching he c rsor, hich means he SELECT s a emen is r n and da a is s ored in he c rsor.

4. Closing he c rsor, hich releases he alloca ed memor .

E ample: E plici C rsors in PL/SQL

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

SELECT fname FROM person;

BEGIN

END;

As sho n abo e, c rsors are declared sing his s n a :

CURSOR c rsor_name IS selec _s a emen ;

Ne , e need o open he c rsor. This is done in he BEGIN block:

DECLARE

CURSOR c_person IS

SELECT fname FROM person;

BEGIN

OPEN c_person;

END;

No , e fe ch he da a from he c rsor in o a ariable.

DECLARE

l_fname VARCHAR2(50);

CURSOR c_person IS

SELECT fname FROM person;

.Da aba eS a .c m
PL/SQL T ial

BEGIN

OPEN c_person;

FETCH c_person INTO l_fname;

END;

We hen ha e o close he c rsor.

DECLARE

l_fname VARCHAR2(50);

CURSOR c_person IS

SELECT fname FROM person;

BEGIN

OPEN c_person;

FETCH c_person INTO l_fname;

CLOSE c_person;

END;

Le 's ri e he ariable o he screen.

DECLARE

l_fname VARCHAR2(50);

CURSOR c_person IS

SELECT fname FROM person;

BEGIN

OPEN c_person;

FETCH c_person INTO l_fname;

DBMS_OUTPUT.PUT_LINE('Name is: ' l_fname);

CLOSE c_person;

END;

The o p sho n here is:

S a emen processed.

Name is: John

I sho s he name of John.

B here are o records in he able. Ho can e handle his i h o r c rsor code?

.Da aba eS a .c m
PL/SQL T ial

E ample: E plici C rsors and Loops

If o r SELECT q er re rns m l iple ro s from an e plici c rsor, e need o se a loop o ge all of


he da a.

We se he same loop as e learned earlier in his g ide:

LOOP

FETCH c rsor_name INTO ariables;

EXIT WHEN c rsor_name%no fo nd;

o r_code;

END LOOP;

Wha does his code do?

I s ar s i h a LOOP, like e' e learned in an earlier sec ion.

We hen ha e a FETCH s a emen , hich ill fe ch he al es of he col mns of o r SELECT


s a emen from a single ro in o he ariables o specif

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 code o an o e ec e is hen r n

The END LOOP s a emen ill end he loop.

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.

Le 's see an e ample.

DECLARE

l_fname VARCHAR2(50);

CURSOR c_person IS

SELECT fname FROM person;

BEGIN

OPEN c_person;

LOOP

FETCH c_person INTO l_fname;

EXIT WHEN c_person%no fo nd;

DBMS_OUTPUT.PUT_LINE('Name is: ' l_fname);

END LOOP;

.Da aba eS a .c m
PL/SQL T ial

CLOSE c_person;

END;

This is similar o he earlier code:

We declare he l_fname ariable, and hen he c rsor as he SELECT s a emen .

We open he c rsor

We s ar he loop

Inside he loop, e fe ch he c rsor in o he l_fname ariable

We o p he al e of l_fname

We loop n il no more records are fo nd

We close he c rsor and end he program

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.

Here's ha is sho n hen ha code is r n:

S a emen processed.

Name is: John

Name is: S san

I sho s o ro s of o p as here are o ro s in he able.

So ha 's ho o can se e plici c rsors i h SELECT s a emen s and se loops o fe ch da a from


ables ha ha e m l iple ro s.

Arra s: M l iple Val es in a Single Variable

In o r earlier e amples, e ha e sed a c rsor and r n a SELECT s a emen o fe ch a al e in o a


ariable.

Wha if e an o s ore m l iple al es b don' an o ha e o crea e separa e ariables for each


of he al es? We an o a oid doing his:

DECLARE

l_fname_1 VARCHAR2(50);

l_fname_2 VARCHAR2(50);

l_fname_3 VARCHAR2(50);

..

Tha ill end p i h a lo of nnecessar code.

.Da aba eS a .c m
PL/SQL T ial

There is a be er a : sing arra s.

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 an arra , s ch as arra _fname.

Pop la e he arra , so each al e in he arra has an inde n mber:

○ arra _fname(1) = 'John',

○ arra _fname(2) = 'S san'

○ arra _fname(3) = 'Mark'

Access he al es hro gho o r code.

So ho can o crea e an arra in PL/SQL? Arra s are crea ed like his:

DECLARE

TYPE fname_arra _ pe IS VARRAY(10) OF VARCHAR2(50);

fname_arra fname_arra _ pe;

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.

E ample: Crea ing a VARRAY

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.

This line is:

TYPE fname_arra _ pe IS VARRAY(10) OF VARCHAR2(50);

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.

We hen specif IS VARRAY(10). This means he pe is a VARRAY, hich is he arra pe in PL/SQL.


The 10 indica es he ma im m n mber of elemen s in his arra . This means an ariable based on his
pe can hold p o 10 al es in i .

Finall , e specif OF VARCHAR2(50) hich is he pe of da a i holds. Yo can crea e pes ha


hold NUMBER al es or an o her PL/SQL da a pe.

Once e ha e declared o r pe, e can hen declare a ariable of ha pe:

.Da aba eS a .c m
PL/SQL T ial

fname_arra fname_arra _ pe;

This code declares a ne ariable called fname_arra i h he da a pe of fname_arra _ pe. We


don' need o specif an hing else beca se ha 's incl ded in he TYPE declara ion.

No ha ? We pop la e he arra .

DECLARE

TYPE fname_arra _ pe IS VARRAY(10) OF VARCHAR2(50);

fname_arra fname_arra _ pe;

BEGIN

fname_arra := fname_arra _ pe('Adam', 'Belinda', 'Charles',


'Debra');

END;

We' e se he fname_arra o con ain fo r differen names.

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

TYPE fname_arra _ pe IS VARRAY(10) OF VARCHAR2(50);

fname_arra fname_arra _ pe;

BEGIN

fname_arra := fname_arra _ pe('Adam', 'Belinda', 'Charles',


'Debra');

FOR i IN 1 .. fname_arra .co n LOOP

DBMS_OUTPUT.PUT_LINE('Name is: ' fname_arra (i));

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 .

This co n is an a rib e of he arra , and i re rns he n mber of records or elemen s in he arra .


I 's be er o se his ra her han j s he n mber 4, beca se he arra si e can change (if o 're
pop la ing i from some here else).

.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.

The o p sho ld sho separa e lines ha displa each of he al es in he arra .

If e r n he code, his is ha e ge :

S a emen processed.

Name is: Adam

Name is: Belinda

Name is: Charles

Name is: Debra

I sho s separa e lines, one for each name in he arra .

So ha 's ho o can se arra s in o r PL/SQL code.

Concl sion

A c rsor is an area in memor sed o hold de ails of an SQL s a emen , s ch as he n mber of


impac ed ro s and he al es re rned from a SELECT q er .

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

Ho can o declare an e plici c rsor?

c rsor_name IS selec _q er ;

c rsor_name := selec _q er ;

c rsor_name IS TYPE OF e plici _c rsor;

Yo can' , beca se e plici c rsors are crea ed a oma icall b Oracle.

Q es ion 2

Wha does he %FOUND a rib e of a c rsor do?

.Da aba eS a .c m
PL/SQL T ial

Re rns he da a from he c rsor.

Re rns he n mber of ro s fo nd b he c rsor

No hing, i on' ork beca se i needs o be ri en in lo ercase.

Re rns r e if a leas one ro is impac ed b he q er , o her ise i sho s false

Q es ion 3

Wha does his code do?

TYPE id_arra pe IS VARRAY(10) OF NUMBER(4);

id_arra id_arra pe;

No hing, i ill sho an error

I ill declare a ne pe of an arra of n mbers, and a ne ariable of ha pe

I declares a ne pe of arra , b does no declare a ariable of ha pe

I crea es a ne able i h o col mns, one as an arra and he o her as a n mber.

Q es ion 4

Ho can o ge he n mber of ro s impac ed b an INSERT s a emen in o r PL/SQL code?

Use he sql%ROWCOUNT a rib e.

SELECT from he able o find ro s inser ed oda .

Yo can' .

Use he sql%NUMROWS a rib e.

.Da aba eS a .c m
PL/SQL T ial

Chap e 6: Reco d T pe and B lk Collec

In hi chap er, e'll learn abo :

● U ing da a pe ba ed on able and col mn

● Under anding ha collec ion are

● U ing he BULK COLLECT ke ord o fe ch da a in b lk

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

In earlier code, e declared ariable o hold al e e loaded from he da aba e.

DECLARE

l_fname VARCHAR2(50);

BEGIN

SELECT fname

INTO l_fname

FROM person;

DBMS_OUTPUT.PUT_LINE('The name is ' l_fname);

END;

The l_fname ariable i a VARCHAR2(50). Thi j happen o be he ame a he able e crea ed:

CREATE TABLE person (

fname VARCHAR2(50)

);

B ha if he able declara ion change ? We ho ldn' be forcing o r code o be he ame a he


able in hi a , beca e e o ld ha e o change o r code.

There i a be er a o do i , and ha ' ing he %TYPE a rib e.

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 .

The code o do ha look like hi :

DECLARE

.Da aba eS a .c m
PL/SQL T ial

ariable_name table_name.col mn_name %TYPE;

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.

E ample - U ing he %TYPE A rib e

We can pda e o r code o e hi :

DECLARE

l_fname person.fname%TYPE;

BEGIN

SELECT fname

INTO l_fname

FROM person;

DBMS_OUTPUT.PUT_LINE('The name is ' l_fname);

END;

The o p of hi code i :

Statement processed.

The name is John

Thi make o r code ea ier o main ain.

E ample - T o Variable U ing %TYPE

Yo can declare m l iple ariable ha e he %TYPE a rib e if o need o.

Le ' a o r able looked like hi :

CREATE TABLE person (

fname VARCHAR2(50),

lname VARCHAR2(50),

salar NUMBER(8)

);

INSERT INTO person (fname, lname, salar ) VALUES ('John', 'Smith',


50000);

.Da aba eS a .c m
PL/SQL T ial

We ha e one record:

FNAME LNAME SALARY

John Smi h 50000

O r PL/SQL code can o p hi record b ing ariable and he %TYPE a rib e.

DECLARE

l_fname person.fname%TYPE;

l_lname person.lname%TYPE;

l_salar person.salar %TYPE;

BEGIN

SELECT fname, lname, salar

INTO l_fname, l_lname, l_salar

FROM person;

DBMS_OUTPUT.PUT_LINE('The name is '

l_fname ' ' l_lname ' ith a salar of ' l_salar );

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.

The name is John Smith ith a salar of 50000

Ro T pe

Ano her ef l fea re of PL/SQL i he abili o crea e a ariable ha ha he ame da a pe of an


en ire able ro .

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;

l_salar person.salar %TYPE;

BEGIN

.Da aba eS a .c m
PL/SQL T ial

Thi ma eem OK, b ha if e an o e 5 or 10 col mn ? We o ld need o declare a lo of


ariable .

In PL/SQL, o can declare a ingle ariable and e he pe of i eq al o he en ire ro . I kind of


ork like an arra , here each elemen or a rib e i eq al o one col mn.

We can do hi ing he %ROWTYPE a rib e:

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.

Ho do e acce he al e ? We e ariable_name.col mn_name.

Le ' ee an e ample:

DECLARE

l_ro _person person%ROWTYPE;

BEGIN

SELECT fname, lname, salar

INTO l_ro _person.fname, l_ro _person.lname, l_ro _person.salar

FROM person;

DBMS_OUTPUT.PUT_LINE('The name is '

l_ro _person.fname ' ' l_ro _person.lname ' ith a salar


of ' l_ro _person.salar );

END;

Thi code incl de a fe change :

● 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.

● The PUT_LINE f nc ion e he a rib e of he l_ro _per on ariable. For e ample,


l_ro _per on.fname i he fname col mn from he per on able.

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;

Thi ork imilar o ing a able. The o p of hi q er i :

Statement processed.

The name is John Smith ith a salar of 50000

PL/SQL Collec ion

PL/SQL incl de a fea re called collec ion . A collec ion in PL/SQL i a e of al e ha ha e he


ame da a pe. I ' imilar o an arra ha e' e learned abo earlier in hi g ide, b here are
e eral difference .

Objec T pe N mbe of Inde T pe Den e o Spa e Can be an Objec


Elemen

Varra Fi ed N mber Den e Ye

Inde B Table Variable S ring Ei her No

Ne ed Table Variable N mber Ei her Ye

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

An Inde B Table (al o kno n a an a ocia i e arra ) i a pe of ariable ha ore ke - al e pair .


Like arra in o her programming lang age , he ke can be n mber or ring .

Crea ing a ariable ing an Inde B Table i done in he follo ing a :

TYPE t pe_name IS TABLE OF element_data_t pe [NOT NULL] INDEX BY


inde _data_t pe;

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

TYPE first_name IS TABLE OF VARCHAR2(50) INDEX BY PLS_INTEGER;

name_list first_name;

BEGIN

.Da aba eS a .c m
PL/SQL T ial

..

END;

Ho can e pop la e and e hi li ? We add i em , or elemen , o he li b pecif ing he ke in


bracke and ing he := mbol:

name_list(1) := 'John';

We can add e eral elemen o hi ariable:

DECLARE

TYPE first_name IS TABLE OF VARCHAR2(50) INDEX BY PLS_INTEGER;

name_list first_name;

BEGIN

name_list(1) := 'John';

name_list(2) := 'S san';

name_list(3) := 'Mark';

name_list(4) := 'Debra';

END;

Ho do e acce he al e in he li o o p hem? We can e he FIRST and NEXT f nc ion of


he ariable, a ell a a loop. The e f nc ion are b il in o he Inde B Table da a pe.

O r code look like hi :

DECLARE

TYPE first_name IS TABLE OF VARCHAR2(50) INDEX BY PLS_INTEGER;

name_list first_name;

c rrent_name_id PLS_INTEGER;

BEGIN

name_list(1) := 'John';

name_list(2) := 'S san';

name_list(3) := 'Mark';

name_list(4) := 'Debra';

c rrent_name_id := name_list.FIRST;

WHILE c rrent_name_id IS NOT NULL LOOP

DBMS_OUTPUT.PUT_LINE('The name is ' name_list(c rrent_name_id));

c rrent_name_id := name_list.NEXT(c rrent_name_id);

.Da aba eS a .c m
PL/SQL T ial

END LOOP;

END;

There i a lo o ake in here:

● We ha e declared a ne ariable called c rren _name_id hich ore he inde of he


collec ion, and i ed for he loop.

● The name_li .FIRST ill re rn he inde of he fir elemen , hich ha been ored in he
c rren _name_id ariable;

● A WHILE loop ill loop hro gh he name_li and o p he al e of he name_li elemen .

● The c rren _name_id ariable i incremen ed ing he name_li .NEXT f nc ion.

The o p of hi code i :

Statement processed.

The name is John

The name is S san

The name is Mark

The name is Debra

E ample - Inde B Table i h Selec Q er

Yo can al o e an Inde B Table i h a SELECT q er on he da aba e.

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

SELECT fname, lname, salar FROM person;

TYPE col_person IS TABLE OF person.fname%TYPE INDEX BY PLS_INTEGER;

person_list col_person;

ro co nter PLS_INTEGER := 0;

BEGIN

FOR i IN c_person LOOP

ro co nter := ro co nter + 1;

person_list(ro co nter) := i.fname;

DBMS_OUTPUT.PUT_LINE('The name is ' person_list(ro co nter));

.Da aba eS a .c m
PL/SQL T ial

END LOOP;

END;

The o p ill ho :

Statement processed.

The name is John

The name is S san

The name is Mark

The name is Debra

So ha ' ho o can e an inde b able, or a ocia i e arra , in PL/SQL.

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;

The n a for crea ing one i :

TYPE t pe_name IS TABLE OF element_data_t pe [NOT NULL];

ariable_name t pe_name;

We declare he name of he pe and he elemen pe, hen e declare a ariable of ha pe.

An e ample of hi in ac ion can be done b modif ing he e ample from earlier:

DECLARE

TYPE first_name IS TABLE OF VARCHAR2(50);

name_list first_name;

BEGIN

name_list := first_name('John', 'S san', 'Mark', 'Debra');

FOR i IN 1 .. name_list.co nt LOOP

DBMS_OUTPUT.PUT_LINE('The name is ' name_list(i));

END LOOP;

END;

Thi i le code han earlier e ample , b i ho he concep of a Ne ed Table.

The o p of hi code i :

Statement processed.

The name is John

.Da aba eS a .c m
PL/SQL T ial

The name is S san

The name is Mark

The name is Debra

When To U e Inde B Table , Ne ed Table , or VArra in PL/SQL

We' e learned abo Inde B Table , Ne ed Table , and Varra . Ho do e kno hen o e each
of hem?

Oracle ha ome ​recommenda ion ​.

When o e an Inde B Table/A ocia i e Arra :

● 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 he inde al e are no con ec i e

● When here i no a e n mber of inde al e

● Yo need o dele e ome of he elemen

When o e a Varra :

● The n mber of elemen i kno n in ad ance

● The elemen are all acce ed in order

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.

Ho e er, i can al o make o r program q i e lo if he are no ri en correc 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.

Le ' a e had hi PL/SQL code ha pda ed he alar in o r per on able.

Here' o r e p da a.

DELETE FROM person;

INSERT INTO person (fname, lname, salar ) VALUES ('John', 'Smith',


20000);

.Da aba eS a .c m
PL/SQL T ial

INSERT INTO person (fname, lname, salar ) VALUES ('S san', 'Jones',
30000);

INSERT INTO person (fname, lname, salar ) VALUES ('Mark', 'Blake',


25000);

INSERT INTO person (fname, lname, salar ) VALUES ('Debra', 'Carlson',


40000);

Here' o r PL/SQL code.

BEGIN

FOR c rrent_rec IN (SELECT fname

FROM person) LOOP

DBMS_OUTPUT.PUT_LINE('Name: ' c rrent_rec.fname);

UPDATE person p

SET p.salar = p.salar + 1000

WHERE p.fname = c rrent_rec.fname;

END LOOP;

END;

The o p i :

1 ro (s) pdated.

Name: John

Name: S san

Name: Mark

Name: Debra

In hi code, e ha e a q er ha elec name . We loop hro gh hi collec ion and pda e he


per on able for each en r in he collec ion, hich mean i r n he UPDATE a emen fo r ime .

We can r n a SELECT a emen o check he ne al e .

SELECT * FROM person;

FNAME LNAME SALARY

John Smi h 21000

S an Jone 31000

.Da aba eS a .c m
PL/SQL T ial

Mark Blake 26000

Debra Carl on 41000

We can ee ha each of he alar al e ha e been increa ed b 1. Ho e er he UPDATE a emen


ha ran 4 epara e ime . Thi i ome hing e an o a oid.

We al o an o a oid ing a c r or for loop a e ha e here. A c r or for loop i here e ha e a


FOR loop ha incl de a SELECT q er in i cri eria. I allo o o loop hro gh each record and
proce i , a e ha e done in o r code.

Ho e er, a c r or for loop i lo a i proce e each ro indi id all . I al o perform a con e


i ch be een he SQL engine (r nning he SELECT q er ) and he PL/SQL engine ( he FOR loop)
There are be er a o do hi : ing a fea re called BULK COLLECT.

BULK COLLECT allo o o fe ch all ro from a SELECT q er in o a collec ion in a ingle


a emen . The SQL code i r n once, and he remainder of he logic i performed in PL/SQL. Thi
grea l red ce he con e i ching be een SQL and PL/SQL, impro ing he performance of o r
code. S e e Fe er ein (and man o her ) ha e ​ ri en abo he benefi ​ of ing BULK COLLECT.

E ample - BULK COLLECT

So ho do e do hi ? We can in rod ce a ariable o hold o r da a, and replace he c r or for loop


i h a SELECT and BULK COLLECT:

DECLARE

TYPE name_t pe IS TABLE OF person.fname%TYPE;

name_list name_t pe;

BEGIN

SELECT fname

BULK COLLECT INTO name_list

FROM person;

FOR i IN 1 .. name_list.co nt LOOP

UPDATE person p

SET p.salar = p.salar + 1000

WHERE p.fname = name_list(i);

END LOOP;

.Da aba eS a .c m
PL/SQL T ial

END;

The change e ha e made here are:

● We' e declared a ne TYPE called name_ pe, hich i a able of al e of he ame pe a


he per on.fname col mn.

● We' e declared a ne ariable ba ed on ha pe, called name_li .

● We' e r n a SELECT a emen hich elec he fname col mn in o he name_li ariable,


ing BULK COLLECT. Thi mean all al e from he q er are added in o hi collec ion.

The loop i hen r n ba ed on he da a alread loaded in o he name_li ariable.

The o p i :

1 ro (s) pdated.

Name: John

Name: S san

Name: Mark

Name: Debra

Thi impro e he performance of he SELECT a emen . B ha abo he UPDATE a emen ?

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.

Ho e er, if o ha e logic ha mean o can' do hi , o can e a fea re called FORALL.

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 .

To do hi , change he code o en re he UPDATE a emen i in ide a FORALL:

DECLARE

TYPE name_t pe IS TABLE OF person.fname%TYPE;

name_list name_t pe;

BEGIN

SELECT fname

BULK COLLECT INTO name_list

.Da aba eS a .c m
PL/SQL T ial

FROM person;

FORALL i IN 1 .. name_list.co nt

UPDATE person p

SET p.salar = p.salar + 1000

WHERE p.fname = name_list(i);

END;

Thi ill r n he UPDATE a emen once on he da aba e.

Yo can check he before and af er ing hi code:

SELECT * FROM person;

DECLARE

TYPE name_t pe IS TABLE OF person.fname%TYPE;

name_list name_t pe;

BEGIN

SELECT fname

BULK COLLECT INTO name_list

FROM person;

FORALL i IN 1 .. name_list.co nt

UPDATE person p

SET p.salar = p.salar + 1000

WHERE p.fname = name_list(i);

END;

SELECT * FROM person;

Thi ho he SELECT q er re l before he code:

FNAME LNAME SALARY

John Smi h 20000

S an Jone 30000

Mark Blake 25000

.Da aba eS a .c m
PL/SQL T ial

Debra Carl on 40000

And he SELECT q er re l af er he code:

FNAME LNAME SALARY

John Smi h 21000

S an Jone 31000

Mark Blake 26000

Debra Carl on 41000

So ha ' ho o can e bo h BULK COLLECT and FORALL o impro e he performance of o r


PL/SQL code. If o an o learn more abo he e fea re , read hi ar icle: ​B lk Proce ing i h
BULK COLLECT and FORALL​.

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

Wha doe %TYPE le o do?

● No hing, i ' no a alid command in PL/SQL.

● I le o declare a ariable ha i ba ed on he da a pe of a col mn.

● I le o declare a ariable ha i ba ed on he da a pe of all col mn in a able.

● I le o define a ariable a being en ered or ped in b he er.

Q e ion 2

.Da aba eS a .c m
PL/SQL T ial

Wha ' one difference be een Inde B Table and Ne ed Table?

● An Inde B Table le o pecif he da a pe of he inde .

● No hing, he are bo h he ame

● A Ne ed Table onl ork i h ne ed SQL a emen

● An Inde B Table need a able i h an inde on i .

Q e ion 3

Wha ' rong i h hi code (a ming he emp_li e i and he emplo ee able e i )?

FORALL i IN 1 .. emp_list.co nt LOOP

UPDATE emplo ee

SET ears = ears + 1

WHERE emp_name = emp_list.emp_name;

END LOOP;

● Yo can' r n a FORALL a emen on an UPDATE a emen .

● The FORALL ke ord doe n' e i .

● FORALL i no a loop o i ho ld no ha e he LOOP and END LOOP a emen .

● No hing, i ill r n cce f ll .

Q e ion 4

Wh ho ld o e BULK COLLECT?

● To red ce he i ching be een PL/SQL code and SQL code.

● Yo ho ldn' e i a all a i ' lo .

● To ge da a from large able , b no mall able .

● I ' req ired o declare collec ion ariable .

.Da aba eS a .c m
PL/SQL T ial

Cha e 7: Ne ed Bl ck a d Package

In this section, o 'll learn:

● What nested blocks are and ho to create them

● What packages are, h o sho ld se them, and ho to create them

What is a Nested Block in PL/SQL?

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.

Wh o ld o do this? There are a fe reasons:

● 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.

● To handle e ceptions separatel . If there is an iss e in part of o r code, o ma ant to


handle that separatel and then contin e ith the e ec tion of o r main code.

A standard PL/SQL block looks like this:

DECLARE

o _ a iable ;

BEGIN

o _code;

END;

A nested block goes inside the BEGIN and END ke ords:

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.

E ample: Nested Block

Let's see an e ample of a nested block.

DECLARE

l_ ala e on. ala %TYPE;

l_fname e on.fname%TYPE := 'John';

BEGIN

SELECT ala

INTO l_ ala

FROM e on

WHERE fname = l_fname;

BEGIN

UPDATE e on

SET ala = l_ ala + 5000

WHERE fname = l_fname;

DBMS_OUTPUT.PUT_LINE('Sala da ed.');

EXCEPTION

WHEN OTHERS THEN

DBMS_OUTPUT.PUT_LINE('E o da ing able: ' SQLERRM);

END;

DBMS_OUTPUT.PUT_LINE('Mo e code he e.');

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.

Here's hat the o tp t sho s:

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

l_ ala e on. ala %TYPE;

l_fname e on.fname%TYPE := 'John';

BEGIN

SELECT ala

INTO l_ ala

FROM e on

WHERE fname = l_fname;

BEGIN

UPDATE e on

SET ala = l_ ala + 5000

WHERE fname = l_fname;

DBMS_OUTPUT.PUT_LINE('Sala da ed.');

EXCEPTION

WHEN OTHERS THEN

DBMS_OUTPUT.PUT_LINE('E o da ing able: ' SQLERRM);

END;

DBMS_OUTPUT.PUT_LINE('Mo e code he e.');

END;

The o tp t is sho n:

1 o ( ) da ed.

E o da ing able: ORA-01438: al e la ge han ecified eci ion


allo ed fo hi col mn

.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").

So that's ho o can rite and se nested blocks.

Let's take a look at another concept in PL/SQL: packages.

What is a Package in PL/SQL?

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?

There are se eral reasons h o sho ld se packages for o r PL/SQL code:

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.

What is a Package Specification?

.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.

Ho can o create a package specification?

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:

CREATE PACKAGE o de _ hi ing AS

PROCEDURE calc_ hi ing(de _co n VARCHAR2);

END o de _ hi ing;

This code sho s a fe things:

● A ne package is created, called order_shipping.

● It contains a single proced re called calc_shipping.

● The proced re takes one parameter: dest_co ntr .

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.

What is a Package Bod ?

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:

CREATE PACKAGE BODY o de _ hi ing AS

PROCEDURE calc_ hi ing(de _co n VARCHAR2) AS

l_fee hi ing_look . hi ing_fee%TYPE;

BEGIN

SELECT hi ing_fee

INTO l_fee

FROM hi ing_look

.Da aba eS a .c m
PL/SQL T ial

WHERE o ce_co n = 'USA'

AND de ina ion_co n = de _co n ;

DBMS_OUTPUT.PUT_LINE('Shi ing fee i ' l_fee);

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.

E ample of Using a PL/SQL Package


We ha e a package and package bod declared and created on the database, after r nning the code
abo e.

Let's set p the sample data, and r n the package code.

CREATE TABLE hi ing_look (

o ce_co n VARCHAR2(100),

de ina ion_co n VARCHAR2(100),

hi ing_fee NUMBER(10,2)

);

INSERT ALL

INTO hi ing_look ( o ce_co n , de ina ion_co n , hi ing_fee)


VALUES ('USA', 'USA', 5)

INTO hi ing_look ( o ce_co n , de ina ion_co n , hi ing_fee)


VALUES ('USA', 'UK', 18)

INTO hi ing_look ( o ce_co n , de ina ion_co n , hi ing_fee)


VALUES ('USA', 'F ance', 20)

INTO hi ing_look ( o ce_co n , de ina ion_co n , hi ing_fee)


VALUES ('USA', 'Canada', 7)

SELECT * FROM d al;

.Da aba eS a .c m
PL/SQL T ial

No e can check the shipping_look p table.

SELECT * FROM hi ing_look ;

SOURCE_COUNTRY DESTINATION_COUNTRY SHIPPING_FEE

USA USA 5

USA UK 18

USA France 20

USA Canada 7

We sho ld ha e all e need to r n o r package code.

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

S a emen oce ed.

Shi ing fee i 18

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.

Some impro ements to this package co ld be:

● Ret rn the shipping_fee al e from the proced re, rather than sho it sing PUT_LINE.

● Add an e ception section to handle al es that are not fo nd in the table.

● 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?

● Yes, this is called a nested block.

● Yes, b t onl if both blocks contain a DECLARE section.

● Yes, b t o can onl ha e t o at the most.

● No, this is not allo ed in PL/SQL.

Q estion 2

What is the difference bet een a package specification and a package bod ?

● Nothing, the are t o ords that mean the same thing.

● A package specification is part of PL/SQL and a package bod is not.

● A package specification contains the p blic information, s ch as f nction names. A package


bod contains the inner details of those f nctions.

● A package specification contains the details of f nctions, and a package bod contains onl the
names and parameters.

Q estion 3

What's rong ith this code?

CREATE PACKAGE em _calc AS

PROCEDURE calc_bon (em _id NUMBER);

END em _calc;

CREATE PACKAGE BODY em _calc AS

PROCEDURE calc la e_bon (em _id NUMBER) AS

BEGIN

UPDATE em

SET bon = ala * 0.1

.Da aba eS a .c m
PL/SQL T ial

WHERE id = em _id;

END;

END em _calc;

● Nothing, it orks fine.

● Yo can't call an UPDATE statement inside a package.

● The proced re name in the bod is different to the specification.

● Yo can't se parameters for proced res in packages.

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.

● Nothing, the error is alread handled so no e tra treatment is needed.

● This is not alid as errors can't be handled in nested blocks.

● 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 f eadi g a d f i g a g i h hi PL/SQL ia . I h e i ' bee he f i


ea i g PL/SQL. I c e a f he ba ic , a d i e gh ge a ed i h i i g PL/SQL c de
a d ki g i h a ica i ha e hi c de.

Tha k agai !

Be B

.Da aba eS a .c

Q A

He e a e he a e he i e i i hi g ide. The b ded a e a e he c ec a e .

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

● Packaged La g age S c ed Q e La g age

● 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:

Wha ke di ed a he ec i he e a iab e a e c ea ed?

● START

● BEGIN

● DECLARE

● VARIABLE

Q e i 2:

Wha d eed i c de he dec a i g a a iab e?

● T .

● The a e, da a e, a d he a e a e a e i ed

● The a e f he a iab e i e i ed.

● The a e, da a e, he a e, a d he d CONSTANT 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:

Wha ' g i h hi c de?

DECLARE

_ adi NUMBER(8);

BEGIN

DBMS_OUTPUT.PUT_LINE('The dia e e i ' 2 * _ adi );

END;

● N hi g. I i a d di a he a e f 16, beca e _ adi i e 8 a d he f ci


i ie i b 2.

● T , ' .

● The c de i a d di a a a e f 2.

● The c de i beca e ca ' c ca e a e a e a e i ha be a e.

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:

Which f he f i g iece f c de i c ec check ha c di i a e e i a IF


ae e ?

● IF ( _i > 10) ( _i < 20) THEN

● IF ( _i > 10 & _i < 20) THEN

● IF ( _i > 10 < 20) THEN

● IF ( > 10 AND < 20) THEN

Q e i 4:

Wha i g i h hi c de?

DECLA E

N MBE (3) := 8;

BEGIN

HILE ( < 5) LOO

DBM O . LINE('L : ' );

:= + 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

Which e f he e a e e i e ab he diffe e ce be ee a ced e a d a f ci ?

● The a e b h he a e.

● F RET RN , ' .

● P ced e ca ake IN a a e e a d OUT a a e e .

● P ced e ca be ed i eg a SQL, b f ci ca .

Q e i 2

Wha d e he OR REPLACE ke dd a a f he CREATE PROCEDURE CREATE


FUNCTION a e e ?

● 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 " .

● I' a a ica he c ea e he ced e.

● R he "RUN ced e_ a e" a e e .

.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 ;

● Y ca ' , beca e e ici c a e c ea ed a a ica b O ac e.

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

● N hi g, i ' k beca e i eed be i e i e ca e.

● R ,

Q e i 3

Wha d e hi c de d ?

E I A A (10) OF N MBE (4);

● N hi g, i i h a e

● I ,

● I dec a e a e e fa a ,b d e dec a e a a iab e f ha e

● 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

H ca ge he be f i ac ed b a INSERT a e e i PL/SQL c de?

● %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.

● I e defi e a a iab e a bei g e e ed ed i b he e .

Q e i 2

Wha ' e diffe e ce be ee I de B Tab e a d Ne ed Tab e?

● 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 ;

● Y ca ' a FORALL a e e a UPDATE a e e .

● The FORALL ke dd e ' e i .

● FORALL LOOP END LOOP .

.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 .

● I' e i ed dec a e c ec i a iab e .

Cha e 7

Q e i 1

Ca ha e a BEGIN a d END b ck i hi a he BEGIN a d END b ck?

● , .

● 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

Wha i he diffe e ce be ee a ackage ecifica i a d a ackage b d ?

● N hi g, he a e d ha ea he a e hi g.

● A ackage ecifica i i a f PL/SQL a d a ackage b d i .

● A , .A
.

● A ackage ecifica i c ai he de ai ff ci , a d a ackage b d c ai he


a e a d a a ee .

Q e i 3

Wha ' g i h hi c de?

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.

● Y ca ' ca a UPDATE a e e i ide a ackage.

● T .

● Y ca ' e a a ee f ced e i ackage .

Q e i 4

Wha ha e if a e i f d i a e ed b ck, a d i i ha d ed b he EXCEPTION ec i a di


a ed a DBMS_OUTPUT.PUT_LINE f c i ?

● 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

You might also like