Rdbms Unit 6
Rdbms Unit 6
objecthves :
PL/SQL RecoYds
sUb PYo9Yams
Proceduxes
Functions
Ecepthon Handiing
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
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)
any
peri Dd Dperato
datatype. DY mcmbey.'acces s, oY
dot (•) Opeiato eod
A Reo type can accept. thedata.
Y
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
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
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
Chaitul
Brgio
. 5 Hàdík
Rodtype
Ghopal90,c0m
from customers
Custone-TeC.sustomei
Begin
komol
- CuT). Yow typc,
Ex :
Books in
ing
a ibraYY
attrib utes
you
abocut each
book.
Pashcway
sub pr091a ms
task.
"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.
(Dynamc ty pe).
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
Subprogram valus Can be changed. Syotax ?> Create LoY epl aca pDce
due
Procedure-Name (PaYametey-Name
1 n datatyr,
be a vauable
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
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;
Square nomla);
6 out Pavametex
Rturn Stattment
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
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
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
Dther uSers
USe DUT Payameto to USe YefuY) to yetuy the
attect multple applicatan
Modify ne YDutine to
Yetusn the Value. Value.
Re cuvsIon:
calls.
Via tunction
YecuYSIon
PLÍSQL does. suppoxt
itse if
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
endj
>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
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
)
in
>cYeate OY PYocedqYe
Yeplace
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
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;
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
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
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
more.than
cannot
i: t oatidNumbey' giving stving:
i.
otnT tDral-courSc 7.
|
Storage - Eyoy
of
Rascd when
menmoy
P2/s0L Yanout
a. Expl|cit cuY
SOYs.
St atement one at a
tume
-t Ye fun Volte s TRUE it DML Ofect
7. NoT FOUND
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)
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.
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 ::
.
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
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;
ExtYa
3 vICKy C
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
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
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:
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 >
c1 find site
30pen
ste id 91tribuH;
Yetu Yn
end CuY-nO me ,otr.nomf.
of cuYSOYS
Advantoges
Retuxnin9
one Yowo bloct ot roos rorn the ced event otu ot
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
a uthoyiahon.
Le elm9ge Tt creates on
th
Teplaces an
he trígqer-hame.
existing
: 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:
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
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
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
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.
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
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
SQL> Declare
Sic int! >&sid
Begros
Studentsmayks. indmayks(sic)
oPEntu valu fox sid4
End;
Advantaqes ot PacCkoges:
MDdul avity
Added functionaity
Better - perfomance