Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
18 views26 pages

Rdbms Unit 6

The document provides an overview of PL/SQL, focusing on advanced procedural language concepts such as records, subprograms, and exception handling. It includes examples of creating and using records, as well as defining and invoking procedures and functions. Additionally, it discusses different types of records and their applications in database programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views26 pages

Rdbms Unit 6

The document provides an overview of PL/SQL, focusing on advanced procedural language concepts such as records, subprograms, and exception handling. It includes examples of creating and using records, as well as defining and invoking procedures and functions. Additionally, it discusses different types of records and their applications in database programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

nit -6

Advanced PL TProceduval languag<J/saL


[stru Ctuy ed Quexy languagJ.

objecthves :
PL/SQL RecoYds

sUb PYo9Yams
Proceduxes
Functions

Recuvsion with Example program


|stoY Cd pYo cedu es

Ecepthon Handiing

CuYsot with Example programs

oith Example programs


TYi9gers
Packag es with ample
Ex progYams.
PL/SQL Recovds i- |for e1aniple Books in a
libyavy
ata Styu ctuyes h 41a ck the atn'butes/ tie (ds / (olurnns
Recovd s aye Composite about

dittevent Components
called field S/
Columne
each book, such as Title
up of
data types: hu thot,
bave diHesent
chad
These fietds can subject,
Vachov 2 numbu

Recordtype Syntax
Cveating

NUmb Datc
Type TYpename is Recovd
(olumns
of yelated data iteme columnname4 dlatatype 1l NoTAOLLJ;= Defaut eypressig
is agoup olumnamez atatype 2(NoTWj C:= Deault apresiag
with
in fielos each
Stoved

datatype. thatCan hold


cotu mn.namen' data typc[NoTNULuJ:: Dejauutexpressin
is a data structuxe
Den: A YeCoxd tpes.
aitteyent eCoTOd_name type-ngm
data i tems o

Simílo :
different telds,
ot BoOk- Rec0Yd
cons ists Ez
-RecoYd ta ble
Yow of a database >Deciaye
is Recoxd
tyPE boOk s
Recovd type : 2(3d,
(TiHe vavchar
YecOrd type sa complex datatypc dhics
autho Vavcha2 l30)

to Create a new data


Subject Vaychar)l3o, &.
allows the prDqYammer
column structuYc. book id Numbe);
type with the desiqne
a
colunn, to tom
iOK books;
one or moYe book 2 boOks;
*It qYOUps
new data type. ACCesSing Fielals:
0un nanmeg the
These columns w) have its
Tb access Held of a YecoYd we cuse

any
peri Dd Dperato
datatype. DY mcmbey.'acces s, oY
dot (•) Opeiato eod
A Reo type can accept. thedata.
Y

Opevato s Coded oa period betwee)


the
coIsh to aces
name,;the
As a single ecord that consists of may e ld that we

Vayiable
Columns.
can
t
accept he value toy one payticula
Cola) Df. a YeCOYd.
0f Reco Yd type
iogvam i Osage
>DeclaYe
YecOYd ROOK 1 tiHcic PDq ramming
typc boOks is
Chay2(So) Rook I authoyi Dennis Ritchie.
(title va
vachar, (30), gOoK IsubjectiPc
autho
(30),
Sabject vaychar2
bookid ANu mbe)i:.
BOOk I boOk-jd12342

BoOK 2 tritle: Rel atfon al Oatabase s


books j FF Coob
book 2 author

;
BOOk
I
boDK books;
BoDk 2 Subject :RDBMS
Begin 2354,
BoOk2 book_id
800K 1 spectication r, Rocotypel
/O7,TyPe
books tite .
1. autboyi
"cprogYam
= Dennis Ritche'o
ming
variade
ATT
Atributes in PL/

RIBUTEE
soL

Z RDtwTYPE ATRI BUrE


book %. Type
declax
='pc';
boor 1-5ubject:
boOk4 boOR-id i=12341; TOS tead f
n9 a clatatp t Can type that_represents
us
vachara vecoYd
be used to

|Such as Numbes, in a tabfc (For


Tow
7tyPe |aYow
Book 2 SpecHica hion eto. We can use can use Dow typ
Yeprsen ts we Y,

s': a ttrib ute.


book 2 .tite = Relatonal Databajc'M T provid es the reCord type
datatyPe
Tt Provides the
vo
book 2 authori =EFcodd' a vaable
basC 0 a da ta H6 at Yepres
en ts a centre
oY VWe) OY
COlumns
ble. a table
book2 sdbject i >RDBNS' Cofu mn to that vayia of

in 6e curs.
selected
book 2 book-id i 2354/ Need:tD know about
kn00) about
-- Print book ecoYds Need not to
4
varia ble datatyPc.
vay'ablt datatyPe.
dbm s-output. puttine tite :bo0k|:titie);
('BO0k 1

Lt a column in a table cannot change


('Book 1authot'Il book), authov);
aatormaticaly
|changes the datatype a

(B0OK 1 Subject :'Nbo0KI Suljat vartable changes accodin

(Book4 book _ia' b ookt k)


b00 9y/Automatícally.

- Print book2 Te co1d syntax!


me>< tab-name
|dbms-output.puttineCBook , < VaY-namtab-Dames <Varòa
title :'lbooky .titig; 3, Row typcj
< colurame 7. tyP
" ('Book, author:")bowky authoy"

CBoDk, Sabject i'llbooky. subjec'


(Book book-td:'l books ,b00R-id)
end;
Example:
Example
>Decia Ye kvaY-name><t tab-nme Îos
(u.stommer
emp.ename. >DeclaYe
V.empname custome nam! Hadik
TYPcj v-tmp cmp. Rowtype rustomet addYe SS Bhopal
6egin 8egin customes salay 90.000
ename into V-empnand em empho =l0
P
Select
Rownu v-tmP ename='v cuIsO Based RecoYd:
from emp wheYe
end; ROwtyPe attribute en ables progrommer to
putine ('Nam
a
The
albm$-outpet
0.cmpname)
; Cseate CUrsov-Based RecoTds.
an
end; pe:TH is named contyo! structue 4sed by

program to point to select Yow 4


application
Reco Yds; a yesutt set .
TYPes of data from
pYovides 3 types of RecoYds!
PLISOL instead bf.exe cuting a query all at on Ce,you Can
Tablc-Based RecoYd use a cusoY to.re ad E PYo cess the quey Tesult
I

2,CuSDY -Based Recod Set one Y0W..at a Hme


3. DSeT-0efnd ReCoYd st s used.to fetch E pYOCeSs the vowS Yetmed
by the sQL Statcment ,one ata tme:
4 Table -B ased Recold;

a pr09ramn Ex:Retei- customes table .Nam Addyer Salasy


-T6e ROITVPE attributes'enable's
LRamesh
Teco 7d: Program: 2
to CIea tetaalC..bascd >Decl ae khiln
ouhik
PEi Ref- Cu stomevstable IDNOMENDDP ES SAA CurS0Y customet -cs, is
3

Chaitul

Select Jcl, name,address tHordit Bhopal|40,060


|Program: 3
>Dectae
Customei- Tec customes

Brgio
. 5 Hàdík
Rodtype
Ghopal90,c0m
from customers
Custone-TeC.sustomei
Begin
komol
- CuT). Yow typc,

Open custome Cur;


Sete ct y into cu stomer -YeC
loop
from cus tomeYS tetch CustomtCurinto custormeY -YeC;
where ias; Ezit ohen custome-Curh Dotfound' 'ncusomer.
e C"cuštomeY-Ttia'r
dbms. 0atput: puttíncCCostoer i:lleustomérivee id); dbms-0utput.put-tin

(customey namui'IJcu stamer.7ec naj end .tdo OP }


en d; 3 k@as hik
(customer addyess W custo mes.a add
Ccustomer solaty :'l! 6 astumer.vec salar)
S. Ha die
c- Komal.
Usey- Detined Recovdsl Record-ype:
BoOks in lib1ar4 (RecoYd 1ype ex)
recod ype
a wes-defined
PPL/sQL provides e (o
define
he diteYnt structuYe, sabprog0ms
al lows you to
ields
consists of diHerent Is a pi09Yan unt/module that peitoms
vecod
mign oanr to rar
hese

Ex :
Books in

ing
a ibraYY
attrib utes
you
abocut each
book.
Pashcway

sub pr091a ms
task.

Qle combined to torm lag progans


The follo
his is basically called the modlay design:
iHe
autho can be invoked by anothe subp70gvam
A subprogrom
subject
of program which is catttd the cal ling prog1am.
(sQL blocks th at an be
De buq a RecoYd. SubpTOqrams aTe named PL

with a set of Parametefs


Syntar: TYpe type-name is Recovd cailed
data typeCsT2e) cYeated i
C colu mn -namC2 can be
4 subprpqYam
data type (sine)), 4t the schema liel
colu mn-namen
TeCoYd- name type-namej înside a package.
>Tnsidea pL [S OL bfo ck..
EX-0
>0rclae
PL/SOL has too types of subprogvams,
type emp-vec is Recovd
subprograms doeshot e
tusn a vaue
Ce-ename emp-e nam e 7ypc, ProceGue. fhese an actiog.
to pevtorm
d)TeCtIy,mainly,cuced
ejob emp:job 7. tyPe,

deptno enp.deptno tyPei subprogramse


Teturn single valu, a
e.
a FunctionsThes
computr sctun a valle.
e-salavy emp.salay 1.ype)' mainly dsed to
Dew-ec emp - Tec, NOTE :
Ohich
Begin tun cions aRe the subprUgrams
new-Yec -enam Procedures
ename,sal,iDh , deptno
into
in the database 0+
selec Can be eYeated G Saved
OT Teted nside
can be Catled
new-Yc- edeptno, data base object6 .They
salay the ofhey bloces also.
have :/ Pavts ot a PL/ sol Sabproran
{rom emp cheYG €mpoo T754 Subprograms
Declavation part:
dbms .outpt- putinel 'ename:'lnew-reC:enamel.
It contains deciavation Of types , CarSO YS, Cons tanly

"lnew -vec.ejo6 -) §
end ; Salary
Vaj'ables,exception s nes ted subprograms.
Exeruta bie pavt! assigh valus Piocedues !
hat
(ontains statementt
Cu dato pe? pioceduye is a subprugrOm that pefoms
Control erecaion s manipulate
a speitic action.

a procedure, specity the name of,the


CTeate
3Excepton- Handling:
Tf deas wi TuD-Hme ervor condons. PrOCeTe,
-end
s
parameters,fs local vaiables €
blocks
begin
ot PL/sqL subpOg rams.
Ndvantages downint
break a program Parameter :
subp09 Tams
manayta ble , coe ll - dehned moduls. The paYa metey is a vaiablc
ox place holdex 0t
the
doatatype through
cohich
Yeusabitity any validPLlsaL
promotes.
values oith
pD motes maintainability. PL/SQL subprDgYam ex change the
2
Betey pevtormance. the majn code.
L+ pYOmetes
YDced
PLIS@L LOnguagc p

can exténd the


Function s ->Ne Paraneters are allbws to qivë input to the
statement.
ats hke new to ettra Ct trom these
trpression € opetafors. subprogvams Subprograms
al ong with
the
Paranmetcrs Shold be detine
Terminologies. ot creatiorn.
subprogram Subprog rams at the time
any Valjd stattmat.i
are Includ ed inthe
vayiàble of callinq
Parameter: Tt is à
eteys
Param
PLLSOL data type:
the pàrajetey fn he subprDgva.

Por.each parämeteY speçiy


MOde
s nome
s-IN,oU INOUT
The datatype o
calling statment 'should be some. .
not menHon ,at
Ttsaatatypc not
7he s2e thedatoatype should
ot
length-l declaYaton
any the time 0f paYametey
t
>Detault val is

(Dynamc ty pe).

is' à keywoYd, ùs ed to:exrt tron Panameter are classiie


Return: 2

the sub prbqram.

INOUT
0TN Payomete: End Proceduacnamej
input to The subprograms.
Used tor qinng -1he
vaiable jnsidc
TH is a Yead-only inSIde suubprog,
the Procedu Ye- WWame specitythe name ot the

|7hei valurs cannot be changed


Proced ure
of ay
Subprogram Can be A(o Replace] opHon allows the mpdl ticaHon

Callin Statement ) parameters .


n
) cristing procedues
VaI abIe o rale oY eYpressI
T6t ophonal parameteY 'st contains n ame, mode

oUT parameter: the.paYameteg.

tor qetting Dutput


from The subprogran. Procedute- body consist the executable Put.
0sed the
write vayi able inside Dt thc is keywoe
Tt is a reod-
inside The subprogYa.
7he ts.keywoYd is us ed instcad

Valus Can be change Procedure gretngs


adways he Replace
paYam eter Should
n calling stmts,
a vaiable • Begin
C'Hello cooYld)
Jbms.output putlinc
INOUT Parameter: End6
getting outpui
Yused giing input& for
tor both

trom the subpYog Ya ms..


thr
IN PaYameteys :T is used to.sendvas to

TE is airead- write Vaiable inside Procedures E its ,Yead only payametey

Subprogram valus Can be changed. Syotax ?> Create LoY epl aca pDce
due
Procedure-Name (PaYametey-Name
1 n datatyr,

Tn caliing stms, parametey, should alcaays

be a vauable

CreatHng a procedwe: declavation secthon;


Syntax :
Begin
Create loy Peplace) Pro ceduve prOce daYe -klame C xecution sectio

[(Pavametea_namc CtN/OUr/INOUD Ezception


handing sect
Exception

endi
Be qn
<Proced ue- bo dy>
C
adolihon
re
E1:>(yeatc proceda
declao tron section,
a iN inttge)
Begin
Ex ecution Section
(oY)
addi Fception handling s echon;
>CTEatz proceduYe
end
IN a intege

E: >yeate pDcedure add


get Valus tror
OUTParametey i 0sed to proedu
(IN a integet
send output orm a oUT b integey
wnte only paramete
o fun ch
on.
Procedure
prDceduu procedue Name >CYete pYDcedaYe add
Syntax; > Create
datatyPe1 o0T (aIN
PoYametey -namne Inttges
2 oUr da tatype e)
Parametes- name b oUT integ
) Syntax - IN-0Ut PaYameteY

dectava tion Sectfon >CYeate: ppcedqre pDceduYe-Namc


Cparameteyi IN OUT data typr,
begin
section,
3eLEuhon éparaites 2 IN OUT datatype
handiing. sechon
erception
end,
additon Ex eCcett pYoceduxe.: eyeette nameC)
E >CYeate proceduYe

a our inkget erec:, nameG


b ouT
tos)
inte ge) Deleting prOced qre :> Dop proce dule pro cedue -Aamy

> Crea t proeedure addition( Drogram


oUr a intege
A Wri a procedave to find min inum numb
oUrb ibtegey
finmin Cx IN Numbe, y. (N unber
PCreafe pyDcedurc
BINOUT Payamneter:
z 0tnumbe
SYnta x ereate proceduve pYD ceduye Name
Parametev, IN dataty pe.

Paramete00tdatatye,
os (6) '|a)
bms 0utput -putline ('squaae
Begio
end;
IF Y<y theo
PL(sQL. ot. MYsOL to add
a procecue
E1sF
tuoo numbers.
2. =4,; noted by ,,used
49,
> DELLEMETER @ keyword, e
End it
to dehne stored procedures, tun chon s, tn'gges
En d;
Declave >(YeatC pybcedure add)
a Dum bej
Begin
o/ >.call add )
Declare a int;
C numberj b int
cint,;
Bego
a'. =28 SET a= l0;
b J0;

fio min ca,b,c))

dbms-outp ut Putin e ('MIN O (Q3,29: 're select C; :


endj
en dj
in MyGOL tor arameter
Qlei MIN G C2 3, as)23. aorite a pLlsau psogram
mo de C).
o. Write a ptlsQL procecduu to tind s à ane q >DELTMETER
nqmbeY UsIng IN OUT mode
PGegte procedursgetpn
(IN TOlno vavchar 2(3o))

~7Ceate procedure su ae nom (r INOUT NUmbe) Begin


pin (21059-4
olp: >tat l qet -22
select * from student wh ere
Begi Pin =ottno7 Acldyess
22$9 -Cm Mumbey
x-X*Xj:. er d;
end;
Declare
a number(5)
Begin

Square nomla);
6 out Pavametex
Rturn Stattment

immediately comple tes the execution of a


outdemo(IN Sbranch
>eate Procdl YE
OUT totol int ) vavchar
subpro9Yam Tetuyns (ontyol to the calte.

Can Contao s seveyoJ Retuyn stmts.


Gegin subprogram
Select+ coun t*)NTD total rom lgn procedurta retuYn stotcment cannot contun
Student ohere byanch = sbranch, an expYlSS)On, but tunction contains Yetuyn Statemegt

end; D/Pi > call Otutdemno


C'csE

>sclect total ,'


tota); syntax :
>yeote o7 Replace tuncion tunction-name
tof al
((ist ot param eter)
Return Yetuyn -datatyp;

Funcfions : declavaton section;


A function is a sabprogram that. Cornputes Begin
Yetu Yns a singl vaes executicn section;

has tuo paðts O spec ification


Fun chion
OBody.
c1cepticn

1ception
sechion ;
| specitication
and ends witf
oith the keyoYd
begin s
t6e.eturn .clà u se, which
tunchi
end

Ex

7CYeate
To make
Replace
fanction

funchon adeley ( IN
n2 IN
Du mbe,
numbe)
Specify the daatype ot the Yetum value.
Retuyn u mbey

o/P;Hd is ;33
2 Function Body beqins with the keycoord Ts
n numpbey (8);
the key word erd follocwed by
and ends with
Beqin
an function n ame
FunctHon body has thyee pavts :a de claratan,
executable.
Yeturn

end
n3j

exception.handlng cal the tunction

Decl aYe

ng number (3);

Begin
adey C",22);
dbms-
hai
output .Putlinc ("add is: 'n);/
PrcqyamO Wyite a PL/soL -Punchon Drogram u calll ng a tuncton
Ye
IN PaYQmetey: >Decla
c numbe (2);
2DELIMETER
Begin
eatt tunction callin come (value INT)
ctotal emp0}
Returns INT
Wbms-output putline (`
total employee -lc)
Begin /p)>sclect
Deciaye 6070 end
incomC IT
SET incoe =0j al With Parametevs

< = 0,00)Do tun cHon Welcome -nsç (PnamelN


white CinCome >(reate oY Repfa e
vavch aY>)
income +value j
vaychQY 2
Setincome >
Refun
Gnd ote ; oP,funcdion -cveatcd
Retuyn incomej
Beqin
end i
Return ('wetcome'l P name);
Detim eto
end;
parametevs
oifhot
a tunction
catting
>Creat tuncton tde m oC)
>oeclaye ofP; welcome sure ch
Retuyn int
mSg varchar 2 (20),:
Begin Begin
Refu yn (select sumlmáyks) to studen msg weltomc _msg- funC'suresh');
end ) dbms- ouf put. put-line

Ob
C ms9)

end
out paametes.
7reatc functon total empe)
Similafie s 6et ween procedure
Retun numbey is 6 function
Both can be called tyomn othey PL /SOL blo cks.
total number(2):- 0;
Begin Both can have as many pavametevs as vequjed
select count (*)INTOTOta)
lBoth aYe trea ted as data basc objects in,PL[sQL.
Avorn employee j o/P: funtior cre ted.
Return total;
end;
van tages stocd between
/mer its/pyes/ DiHOences PyOcedure s Funchions
Benetits

Proceduve s funchion Proceduves Functíons

PeYfoymance Du to: Czecute as a PL/SQL stmt> TvOke as pat of an


Tmpyoved erpression
SeYS.
Avoid Yepairin9 toY mulhple a
No Retuvn datatype. > Must contun Ye turn

VOd PLSOL PasSin 9 at untime datatype.


base. co0 Te turn name, One oY >Must setuyn
cals to the data a single valu
Reuce he no. of
moIe Vales
cannot use in s0l stmt can usc in sOL Stmt
||Zmproved ma intainancc Dueto:
outnes ontinc rthout interteing ote Hused mainly to execute > Used mainly to. psomn
Modity SDme cal ation
cextain process. cul

Dther uSers
USe DUT Payameto to USe YefuY) to yetuy the
attect multple applicatan
Modify ne YDutine to
Yetusn the Value. Value.

YOutne. to eliminat dubl iCat


Mdity or mandatovy to retun Mandafoxy to re tun the
Value.
the value
testing. is
Return datatype wii) RetuYn data type
of
at the time
Improved data secuynty Tntegvity not be specítiec at the mandatoy
(yeation
time
Hsof CYeatíon.
subprn fhat tincti oy isas abpgm hat connputy

Re cuvsIon:
calls.
Via tunction
YecuYSIon
PLÍSQL does. suppoxt
itse if

RecaYS iOns, the Qct-of


a function catting
LOcal
PL (sQL to Cveate
TecuTS ive Caequyes
(F(n-) +Fn -
Er FibonaCi Seies ->tcn) >

Number n] =n*(0-);
FactoYial
hogram :0 Factoxia! nu mbey

7CYe ate oy Sepla ce fun ction tact (r numbe a Fibon a ci senes cothout
usin 9 Recunsion tuncthon
>0eclaye
Retuyn numb
1s
a numbey :0;
numbeY|=1;
Be gin temp number
14 X -0 then n numbe =to

tactorial 6 is 120o numbey;


else
tact (x-)) fact (s) trorn
fi =x 7sele'ct- dival; Begin
end it ,; Wbms -output putline ('Aibonaci'seifes is :)'
fact (S)
Return t/ Wms- output. Putline Ca):
|20
end; puttinc c6),
dbms-output.
caing a tunttion
for LlN.2 --n
Declave P; bonact sees is i

Dom numbes, temp. =a +bi 13S8l>3 S SI32


+actoal number,'
Begin
b temp
ta ctoial fact (num),; dbmsou tput pu tinc (temp):
fl factovía.
clbms-output .puttinc C'actorial'I) numll'is' end doop

endj

LFabt0ie' Fibon a cci Series STO RED, PROCEDuRES

>Teate oY Yeplaic tunctHôn ibln inteqe). H is one which petfovms one oY mOTe Specfic
in PL lsOL block.
Retn intege
whiG can
i6iD soL Statements
>SlECt fib(),b[:)- The series df declavative
Begin tomcuaii be stoYed in the data base cutal0ge.
D3 o header body
A proLedure consi sts

el se
tHeadey consists' of' ame'of the pro cedurc ,paramtes

0f declavation section.
Body onsists
end if

end ; cCeption
secthon

section.
Advantages : of the
aPplicahon
Pocecduye cve at ed

BeteY perfomance improvement cal - Pyocedu Ye.


the data base of the
tya ffic betwee Begin
Reduce the
insertu ses (10, 'vayun)
application

Code yeus ability: Wbms - 0u tput.putliheCYecovd insestedsuccessfutly');


end; DIP i o Name
Disadvantages: 1o.Varun
Tt OCupies moYe memory
of de
pyoviide the
tuncHon ality bugging DYOP -Stoy e
procduve
Does nol
the stoYed pYocedue pr0ceduse nam
syntax: >DYOp pYoceduYe
syntax:
proce durc pY0
e du-nan EY:> DOP pYO Ceduye inset user
>eate or Yeplace
tcParam efey TPaYameto
Erception Handling
[is[As]
during the proqvam extuliy
ton] errOY that ocuYs
ldeclaratton-sec
catled an Frcephon
Begin OY at Yunttme is

to catch such
[evecutabic -section] ta ciitate pvOgYammeYs
PL/soL
in the program
Ercept on eYcepti on biock
Conditions asing
erYOY Condition
lerceptiorn -section is taken aqunst
eaction
End pYOCedaenam s,
TheYe aY e types Dt Cception
usY Tabl? So ned to
Ez: Tosevt YecoY in
-Defined (Pye -defined) Etcephn
O System
Geate user tablè tiYstil Ez.: No-Data 4ound, vae eYY0)
N LED
LoGLN-DE
ett.
(l0} Pnmary key, 2ero-DIV ide
Cre a t Ta blë usey (id nobe
name Va ychay 2l3o Exepti on.
User- Detined

sevtsey. E invat id.-tofal , Invald -ag- ett.

)
in
>cYeate OY PYocedqYe
Yeplace

name, IN Vav chax.


IS

Begin
In seyt into .usey Val ues Cid, Name),

end;
Syntax: Delare
aEeption - 0th-tabl LPvedefin ed Exceniony
< declaYa tion- secHdns custom ers

NAME
Begin Addye ss
< exe u ta ble Comnands)> R 23 Saday
A
2( 20D00
Exception
handinq- Sec Hon s 22 25,000
<excep hon- 3
3,00D
When excephon 1 then 2/ 4S,000
- statement H
CYCep Hon -1 -handling 20 S3.000
then M
When excephon 6s,000

Aid -customer s -d?type = 8,-- fd typc


8:
When othersthen
Erception - hand
Endj
ling-stattment
c-name
C-
dd
Customey .name), type.
Custor ers - acdvess 7. type) ame:A
Addyess '
Bcgin
celect name, Qddres s INTO (name, C-addy
Arom customers
> set sCYVeY put DN; wh ere id c- id;
Declae dbms- output- put-line C'Name:'l c-name)'
a intj D/p Entey the valu tota ID ('Addressll c-oddr'
b int; Enter -lhe v ale totb i o

Excephian
Cint; Dvi sim by o is not PO6o Lohen no-data .found then
Begin e ('NO such customer
Nms-Dutput.put-in
when ofhess then o". NO such customs

c'erro Y');
dbms -output. putint
a/b;
C

dbms-output.putlin c
Erception
( Result ="|l d; )
erd;

Paising Fxcption [Rai sa]/throw.


IJhen zeTODivide then eydo
to thxo w an ez ception, use Roise
d bms -output -putlinc (' Division by o is not possiblg used
by prog Yammei by
End; Ereption ave. 1aised Crplicity

Command RAiSE 0Y D8MS- standaYd Raise

using
tpplicaion - erYoY
(rno> 3) Ihen
PLISOL

Ycepions
facititates
accoding
hey useys to detinc
the

exEpion can be
theiy

Ys ed
(4
Rars

encl

fnsert
e

it ;In vatid -total;

Into student values (Sno


snam,(rn o)

4 Csey - defin o db
using the Rase keyoOd Excephon
invalid -totat 6en
trplicity .
- erYoY When
-9pplicahon
Standad Rasc ·puttine (TDtal no-ot CouYses cannot be
doms-output
move than ):
Syntar: >Declavt Ercep h on
<eCeption -name) end;
Begin
<SOL -Sente nce> PL/s OL Predefined
f < test- (onditon then Erceptions

Rsse e eYcephon name>; Pre c e cd erceptrons in PL/sOL which


n ait erecuttd
end iH
(ohen any databas c Tule is völated by the proqram
evLepion
when ex cep fion -namethen Ex NO data -found Roysed ohen a select into strnt

Statment;
tnd;
L'st of imp pre -defined erceptions.

Ex Student ACCeSS-in
to- -NOLLTt IS Raised when anoll oject is

a vaue.
sname TDtal -coUYSes automati cally oxganised
RotiNO

Any Rajsed when none ot choies in


Case-not-found
the ohen cl ause of case.
Ansh
03 vaues ae
13 pit
Chetan on Inder Raised when duplicatc
Deep-vo in a column
wrth
n affempttd to be stored

>set seTvey Dufput ON; unique index


>declaYe Ente hy value toY sno 3 Invalid -cuYsoY Rajs cd cohen CursOY operatin is

Sno student. Rollno type : Ente the valu to sra :ot


Sname Student. &name7-type;
. not allowEd.
1ool
Råsed hen nyalid npur grvn
type;
no o, couYset

more.than
cannot
i: t oatidNumbey' giving stving:
i.

otnT tDral-courSc 7.

Iike, instead ot int


total Ex ception
when attcmpts to ínvalid
Begin Raise
ToGIN -DENIED
username or passwoYd.
Sname: = & sname
hen scle ct nto slmts
ND.data.found Raised Alby
used o execute SDL Stotement store
chta hose fs
Not
-loggtd ON Rased )hen not
informahon. Retieved -
Statement6elect
Connected

Raistd when PL /sQL has an


CursoY
(an
ACess
Manipul a tion- însevt,vpdote
Del ete ,
¡ogram.Erroy The 6et TOWS
intrynal pyoblem. Set- of the u y SoY halds.
nctrue
when incompatable aYe t00 types 0f cuYGOYS
Raised
Rotye - MiSmatch Theye
data typc girern cuxSDYS
|. împlcit

|
Storage - Eyoy
of
Rascd when
menmoy
P2/s0L Yanout
a. Expl|cit cuY
SOYs.

e/soL I mplict uT6OYS


ohen select into Strt
TDO.m any-rou0s Rajsed
one Yo), The impicit cutsoY s are automatically qeneyated
YeturnS moe than On sQL state ment : is erecuted.
by öYacle_ohile
PValue eryor Rased when ayithmetic conversln
detautt
cuYsovs ave CYeated by to
Tmplcit
z ero-divide Raised when divde a homberbyn
PYOcess the statem ents )hen DML Statemen t

Ee Dnset, Update ,Delete aYe éecuted


CURSOR

when an so sta tement isPro cessed,oracle


oYacle .
prov)des
CUYSOY
soMe
atybutes to
attyb utes
cheCk
knoon
the
by as
status Cf

area known sas- contet


area implicit
(Teates memorY. they. lei
DML Operatrons
(Private seL woTk area).
9tyibute Desciption
area
A cuTsoY s a poin tey to this con tevt
is TRUE it DML Stms

|Tt contains ai intomaton


oeedec foy PYDessra l,FOUND Tt tuyns value
att ect at
ke ineyt,delete 8 update statment
the statement. oY. Séle ct into
least one yow
o toi one oy m0xe
Yos, othevwise
Yeffeyd. to
A cuY SOV is used to proqvam Teturned
talse
Yetuvns
theY0w .yetuYned
S by the squ
Yetch process

St atement one at a
tume
-t Ye fun Volte s TRUE it DML Ofect

7. NoT FOUND

of select into etorn noYO)S,


no Yow
it is Pposite of 2FoUNg.
6i mply
ZTS DPEN! YeluS FAsE, found then
TI always
closrd i- 694Y.
clsc
cuYSOY is automatically afta :sqI. YOW count
total.
sf atement.
-output (totas
B7.Rowcount -execating

by
tye tuyns no. of
DML Statemen k
OUs
selec
affccte
into stat
men
clbms
End
if
putline

O|p, 6
YoOS I| cu stom

Custornex pdoted
ey pdatee)

Enc; Pys cL procedure

NoTE:sOL77isuscd to vepesent h implici


Custonns
sueestetly Ceplete

tursoY att butes

Ez sQL 7. FoUND A
S000
SoL ; LS FOOND ete.
Lucry
7D0o

Exampie:
Customns ta6le
JAddYess salavy
PL 1sQL Ex pli cit cusons. 0ser-defined UYSOYS.
Name |AGE
20,000 CuYSOYs are defined bythe
Ro CKY
22
3

B 22,000 he 'Expliclt
to gain Control ovey Còntext area:
pr0q1ammes

(user)
2 24,000
24 CurS DYS aYe detined In the declayation
3
jplict 0f the PLISQL bloCk.
section
A 30,000 CurSOS aTe Oeated bn 9 6elect statengent

.
rplicik mOYe than one 0 w
)hich YttuYDs.

salary. 8 each, CuYSOS aYe declaxed plicity by he


pdate the table by inceasing er plicit
wjth idenhHers to be. used.
Customes by soOO uSeYs, along
eternine the CUYSOY.
SoL 7. RoLDCO unt is. used to no-
syntax to cveate an erplicit

statem ent;
Affected
CURSOR uYSoY -name 16 select-

are .
heate pYoccdure:" CuySOY woYking proceduYe' steps
Evplicit
>DEclae Declare the cuIsOY to ipital)e in The memog
total -YOWS numbey (2)) the CUYSOY to allocate memoy
i
ve dat
Begio t0. Tetie

.
Fetch the curSoY
Upod ate customers, memoy
cuYsoY to.gelease allocatd
SET Salary =
alayy + SDOO; * dDse the
it sql notfound then ::

dbms-output putline ('No cus tom ex updated


O
Declaye -Ihe cuYSOY : Duery
:10 7etieve he CusSo
name & addyess
Tt defnes the cussoY wth a name and t6e
>Decla7e
cu stomes
associated seect statement.
C-,jd

CusoY RO is (-name custormers.


nam .type
syntax:ORSOR name is E

Stlect: from customers .acddress y. ty p


Seled statemml) C-add
her d-s enp
cORSOR c- Cus to meys S

Eopen tbe cuYSOY : celeck ch name ,acddYess iom


toY the cuYcry ustomeYS;
7t is used to allbtate m emoy
6y Begin
Yttuned
it easy to tefch the YOW
S
moves open C- C45fomers;
into i.

.
Hhe sal Statements
Loop
syntar :OPEN cuYsOY - namej
fetch C-Lcustormers into cid, c-name ,C.ad,
3Fctch the cuYSOY ! ExT Dhen C-customers not found

ST is

Can fetch YOwS


used to acCess
fYom the
one Yow at a
Voliabe
time you
dbm s -output. puttinc lid | 'u cnam l/'l coddh)}

End [Dop
S ntar FETCH CuSoY -nam INTD Vatuable ligt O|P Rocty
cLOSe C-custormeys

( Ex:

clos e -The

Jt i used
ETCH

cuYsor:
I INTD

to yelease
emp-d,emp-Name;

the allocatcd memory


Endj

ExtYa
3 vICKy C

Syntax: Clos e cuYSOT-na mej Examples About cuY SoS


Ey '. cios e Pi;

dImplicit CUYSOY
Pogiam customes table, QueTy i Print no -of YDws deletcd from emp table
1
TD Name 29 Addyess. ,salary >Decl ae -Name
Uai ab le

Pocty 23 20,000 Row- del -NO Nd mber i

22 22,000
lucky Begin

VicK9
24 24,000 Delete tom eop
Shivq 25 2 6,D 00 Roo- del- No:! s0L. Rowcountj
S AKShi )s deleted arel|Rce
30.000 dbmsOutput putl ine(NO.of N
AEhil 20 3S,O00
End
ifs details:
and CORSOR FoR.oop
Acepl tmpno UsING
DeclaYe cuTSoY
în the FoPLoOP, theYesut
0t select query
emp.empNo typs
; = PV-no: Sed
to determine the nurohet ot times the loop
nae emp ename 'tyP ; executed.

.
V- is

V job emp-job type > Declae


V. Sa e mp soi typ°
#Ex: CURSOR C 1S
Select
ename,Sal.le pt
Begin {Yom emp
Sel ec+ ename,Job, Sal into V-namC, vJob, v-so
Begi n
tom Enop whexe empno = noj to1 X N C4

1 SQl y. ound then Loop


Ibms output• putlinc Cx, enam
d6ms - output. .dept |1\21X sa)

Exception
End doop ;
End
when ND.data -founcd then
No. need to mnfion open Fetch command.
dbms.output -putlin e Empno cdoes not exsts); :: Note
because for loop open
End;
fetch a
vaes..

Erplicit -cursoY

| ProgYam:
Evplicit- cuysoY

delimetey
in

tt;
MVSOL
using
functions:

>Declqve cuYsoY name MYsql >

int,site-Name vay chas lra):


>create table site
CORSOR C1 is select ename,sa ,depth o
(site

ie Table: CYeated.
from empj ),C48.'Huda co loy)
insevt into site yauesl 26, Ghatkecay
V.nameempna me ,typ
(i,'hydervabad)
V-nam6 emp sal 2.type; Inserted 3-Y0ws
vdpfno ernp. deptno7+yPC > select troe site ;
Begin name site TD Site-Name
uIfoY

26 i}t-
open c1; dhotkesaY

Huda colony
FETCH (1 INTO VnamcVsal,V deptn 0
HYderabad.
(v-name jinvdcptnol V
dbms-output putiinc
cloSE C4;
reote funcion findsitcid (namc int
Mysq >

-YetuYDS int VOvchaas


Brgin
o
sitic int
deault Via me
>deciaye 4able
CayoY foY
declaYt c4 where (on an hon
site. id
trom site
>select
wheye citt -name= name-in' End

c1 find site
30pen
ste id 91tribuH;
Yetu Yn
end CuY-nO me ,otr.nomf.

of cuYSOYS
Advantoges

to positon at speciie Yows of the


YESult set.

Retuxnin9
one Yowo bloct ot roos rorn the ced event otu ot

CurYEnt position in hè jesultset.


Tiggers:
Yows at%e
moaditcatiornto the
S Suppor ting data
in the vesuilt set.
igge
is invoked by oracde engine
DCcuys.
automati cally

event
CuTYent position
wheneve a sptcified
cohile,loop and invoked YCpeatedly
CuYsDYs Can be fa stey thaQn is stoYed into databasSc
rigge Conditon match.
when specih
tles
Implicit

Automaticaly
cuYsO.
created .
nam
Fplicit.

Detined
CuxsoY
expliaty by the
tyi99er
wits
i's

a speciic
a named PL /sQL pYDgyam

da tabass tabIc.
unit asocia

when select sfatements (usey by pYoiing


automatialy
a
stored pYogYans )ohich ayYe

are executed TYiggcrs are event otuYs


oY red when. sorme
executed
YOL 2. Lt Can fetch nmutiple
> Fetching a single Yows Where to use
table,view, sche
ma,
at tne
a
be defined on the
aftey TYI9geYs Can evènt is associatcd
aufomatically 3.Nceds to close hich the
cioses base coith
eyeution. Dr data in the tollowing
execution. to be executed tvents .
attey are ytten
7nggeYs
has lanquagc) Statemens.
progvammae 4. UserIProqyammer manjpulation
4 PYoviles less
the eniye cont rol:
DML (Database
insert, Delete,
Upoate.
Control to the usevs

SLess etfrcient MOYe


bDL CYeate, Alter DYOP
erYo,Startdo ogon, tog o# , Stap
cttident ope Yation (server
5-
wn).
4data base
ldvant oges
F7epHon - han dlin9 Statements
intonatio on table
ftvent oggin Neing EYepion
End;
eplitation
tables

deved olu mns valu es aTomaicah.


Ginevates ASrseat o0 keplace
tnfov(es yekevential integrity

a uthoyiahon.
Le elm9ge Tt creates on

th
Teplaces an
he trígqer-hame.
existing

Tmposng secuviy insteod would


g specitic: when trigge
In valid ansachons eetorelAtHe/ be executed
Preventng
/oelete >
Insest lupdatc specities DML operation.
Bus intss Yules

rHon YeauiYed Whneve insevt, ulat of co Speciies columnnanhok u


futomatic
upda tcd.
Comands one opeva tcd name
delete

-keep ack ot modihcaton o dat.


oN table. Spcciies iname. of the table
oith

: tri9ger
asOCiat

TYPes of Tiggevs
Parts of a TYIgger you a trigge, yo can
de finc detine no-ot times
when
Tnggciing Event TBefoc,9ttet. însttad oJ 4rigge acHon is tobe eYecutcd.
7Tr99er Rrstri'chon tsingl Row' sTable are
There s typte of Tiggevs
Triqger tctton I Statement level
2.Row -level
Cveating a TnggeY 3: B ctore- tn'g9ey
Syntax: cveate [oy Rpiaci] Triggex Tn9ge seme 49tte tri93ev

S Lnstead of trigger:

{Inset to]lepdate toRJ IDekete. Progrargi Cyeate alatrig9geY


Tot col-Nam sal avy - hanges
hcreate' bY'Téplace ri9gev.display - 8alo
-Na insert oY update ON Custtormers
DN tablte

[Reteenung Dld 4s o New sn: Befoyc dele te oY

feming toy sow


eacs
TfoyEach Yow)
when CNew-Td >)
when (condition)
DeclaYe
Declare
Sa-di numbeY
Declau sectl

Begio Begin
Sal dit = New sal ay-old salavy
Eie(utablc~statements
(od salary'I :oldSol arg); As many Hmes you
ee cuted tolse code ,saley
bms- Dutput p1ine ce is SOO0
('New salavg. olway
Wbms AItteeen
ditevene l sal
eLecution
of above codL agaun!
('sal avy
dbms .Jiterence); After old Solary SDDD
End;
New salavy 30,000
Tyigge v (YCatd
Salary ditesence !5D00
CusloY 3000
AddYesS salary ub,000
Name
BL

SCC
Q,000 Dd New Yeterences ae usCd to ge Cond level
23

3
byd Q,000
QG,000
lote

trigges
. these ae not avalable foy table level

Raj
tnggerS.
quey -the has Sone tr9gr
S
s,000 t you wan to tablc

should se the Aftey keywod


30,00D
goa
a trigs
pYOqYam-O Access he value column
bf insiole

ditference by ProceduYe.
che ck the salary sQL> CYate tigqey tr
sal
>DeclaYe Before ínsert on gmp
total-yDwS number(); foy each Yow
Begin
Begin
Custo ners o thenInal'ng alue
Update it newsal v

Set salavy =salay so00; + C'-2001D, 'salasy shouldGetey


be g-.
Raise -1pp)i cation-rYoY o)
it sgd ,
notfound then gretes -th an

tustom ers pdate): d i


dbms -utputputHin c ('no En

elscit sq4.found then End'


yod (ount Modityin9 a Trgge Y.
clauue
total - YDwS! =sq y.

usind oR veplace
ASQm
trig9 moditied sa
customeys pdata
dbms-ctput. putliht Ctotal -10wsl ttng9e can be
command
OFCYeate triggeY n changd
End Ít: tr-say
oPi old salay i20,00 trigge
End; Pgm: > cYeate oY Replace
Meosaley 2s.000
Before in scrton Eg
solasy drHane
SaDo.
foy each yow
Begin
< -0 th an |onodtepaqvalue than
f
J-Sat
New. be qeates
rons' lsalay should
-EnoÝ
Rojse-4pplicaton
End it,;

End
Enabling oy
a TVgger: amount >l000then
Disabing
ne w. amount
o enable oy DiS able a speaitic triggeY, 9ltey stt
oJP: mys ql>releu y horn
is End 0ccouud
trigge Command used

num
Syntay: D ALTER TYiggcY t9ger-name Enable/Disahl amount
J00
20,000 5D
Ex' Aitey tngqey tr-sat disable' 200 30000.5D
atl b99es of a tahb 300
Syptay foy Enable/ Disablc
Eno ble /orsab6le
Atey table tablc name

E, A1tey table emp adisable atl tri99ers

aIe schema obects that qroups


DYop trig9ev tngger-an
Dcichng a triggeYi sgntay ;i
(Packages ycl ated
PLIsQL ype s,variablcs &
E: oYOp tigge tr-sal;.
iogicain
y
-functions etc
s, Pyo ceduyes

Tigers in MysQL : subprogram


he cntire Package s s
on a
fboded the memory
into

function wthin the


(nom nt, anountdumal a procecduYe
my sql> (Teate ta6le Account when
catled the iist time.
7CYeate triggey ins- SUmi (lo,));
Pockages,
is

Before insest on ACCount


rwo.part
for each yow O Pa cKag sprcitication
oY definitin.
7.@sum - sum t Newiamount ePackagc body
> SET sum'o) toc cl avation p Publi objeci

Vales CIDO,20,0Do S.(20o speciti cation


>Inseyt into AcCOuit |Package that
30000.So, (300,yo0oo,s)J S, Vayiales ,constants,et,
IE declaves the type
The pa ckage.
>InSer ted
can be Yetre d,trom Dutside
>select sum
about the content of
all infoYmation
Tt contans.

MY sq >Deimetes the packag aye


in speciticaion
>CYea te tigge Update-check D6je ct placed
9
bn Atcount

4.
BefoYe Update
Dbjech.|
for each Yo o Public

Begto
it ney-amount <o. then
set new. amount 0
Syntay gtcments The
packagc element are Vam
package Packac.name Package
> (Yeate or YeplaCe ables

ProceduYcs
tis/ AsJ

PyoceduY Specih aton >(Ytatc or replace otax' > Packa9t name . elementname
tun ctins.

pockagc Curioy E' Declaye


'
cJP. snteY
- specihcation; Vaue tort ids
tunctron As
s al
- declayah on; code employee.id7.type asy 20,Go.
Vayiable Ex PrDCe dure & sid;

itype - defin'Hon (sidempoyee, i


Begin
t mp- sal - Hnd say
Exception detinhon Ccode)
CUYsoY ditoHon, End mp- sal ; End SPYUCeduhe name.

Erl packaqe- name


Program
O Package Bocy
y(re ate or Replacc hckage emp- sal
Package Body ! tBegin & Prir aie objecisl Bocly

for all ProceduYe Hnd-sal (sid cmploye


It should. contains detioition subprcgrany e-id typc)
in the
DY CuYsoYs at have been decla¢d
esal employec sala vy I,ty Pe,

sptcihcatron. Begin
alDb al decla Yation pan
-Tt bas private tements select salary into esal
en5 the
|Tt contains the code hat implem from e mployee wheve id rsid;
C'salary - "Mem sa)
Packagc specihcaton. cJbms-output: Putline

Syntay : End id-sal oP:Da ctaqe body cYeatccl.

7(Yeate T Teplace packagc body Pactage harne


En d cmp-sal
[is [AsJ Bocy
Pogiam :Package specitication
PrbceduYe detiiton,
Students
tunct oD
Name
Pyiv a- Vaxiblcdeclaraton:
Rishi
MaTke
189
cursbYi detnh on
Tar un
Begin 3 Varu S86
executable - statemen ts
sTyjan

Pacrage specificahion
body studen&- ma
End j oY Tepla ce Package
Codei s0L> Create
As int);
ykS Csid-
ProceduYc find-ma
End students-maks"
Packagc bocdy (ooe, Sf
Ckage body
or Yeplace pa
aternt.
SQL>CYeate
int)
mayks CSd
MavKs As
find-
Poceduye
S
Smayks int;
Beqin
nfo smaYkS
rorm students
Select mayks
where id =sid;
'M smayel
puthin c('smayks
dbms-output.
End ind- marksj
End stulent- mayks

Pactagc body Cxeateo

Dsing the package clement

SQL> Declare
Sic int! >&sid
Begros
Studentsmayks. indmayks(sic)
oPEntu valu fox sid4
End;

Advantaqes ot PacCkoges:

MDdul avity

tosie applicatton deoigb


8 Intovmation hialing
i: i

Added functionaity
Better - perfomance

You might also like