• An all-iecfuslvc book to reach you cvcrythil1g about Orad.

Pl/SQl ProGramming

,. Ea5.Y, Effective, And

Rehable

• Quick and Eas.y IC4Jmfng in Simple SlOpS

• Most preferred choice worldwide (or learning Oracle ntsQL I>rogr.mming

Oracle PLISOL Programming

mflil.~LIi 1iF1iEPS

Premier12

1982, 2004, Oracle.

All rights I

10.1.0.2.0 - Production on F

to:

Database 10g Enterprise Edition Release the Partitioning, OLAP and Data Mining op,

SET SERUEROUTPUT OM

CREATE OR REPLACE PROCEDURE salary (eno II e_sal HUMBER; BEGIH

I L1

©CorJYri~bt b~ Drceratccb PJe'S5, 19-.4.. An:.s.1rlRol!.u. Daryol,g;tPj, Nl.':w Delhi-! 100(J;2

This 'I::MJ.oL:: ,my tloOl be duplicated 1:n :aoy wOIy \Io'iloou[ 1~1!Xpt'(!S.:S wrh[~ consent of Inc pub 1 iStJ~f ~ ~~i!;:.," in tile form, of b_r1(!f i::!C,iX,I'PU or q-uQt!!,tions for the pu:..I'f.'05'CS of review. 1'[.11,,':. inlbm13ij(m ccntnlucd i't.e{(!i_t\ ls for .beJ'lCr!iOO1:d uso of the reeder uod rnJ.Y not 'be incorpcretcd m lIny commercial prugr.lln~"Dtln~r books. databuscs, or uny klnU cf scftwurc '_"·jIOOut wrhkfl consura of the p:uD1i:~hct_ MaUng copies o.fdilS ool}'k OF Lin)' portion for atI)' purpose m!I'Lir thau yoor OWr.I is, a 'violati 00 'Of o;;opoyrigln laws,

F III

l.trnits ef U~bili~)'JdifiCll!lilm'f{lf W:;llrnr!.~~'; Th~ i:!!ulhor aod pubnsher !:i,fl v e USi."1;! tbcir tcsr t"ffor1:.50 in pr~-p:;!!rmg this book. Th.1.!' 2IulhOT make 00- representation or warramles ...... Llh respect to the IIIL-:.clll""doI.>), nr complrt~[le;.'i of 1M: tool~Ii.H of 'l1ii:s. bock. .afJLi ~iflc;a]ly disclaim .(illY implied v."<iJTiinlili::S of TfIt.'TI:Iw:nI:iibi~ily C!T fitne15 uf'.fitIy peniculnr purpose. There nrc no warrant! 1::.5 which extend beyond the descripdons 1o":L)I'lI:!lnOO in thi~ pnrn~_ No warranty TIlil.)' be ctcatcd [II extended 1:1)' sales fl:'pre_~I::Dl::iti .... ..:=~ 0-1 ..... rittcn ~Ic~ Q'LilI1::rlill!_ The ac.t:1It'"..k.y end completeness uf the infbrmaticn pr.:Nidtd hL'\t(:lll end lhe (Ipti1_iOl1.:!i s.I~loI:d hereln nre nl'll guaranteed or ..... arr .. uued to produce ~my p .. mL~IJ];illn; resuns, and Ihe advice and ;51"'.1~ies cunrained herein may not be :!>lJil;;lble for e~~')' indivtchl;;J,l. Neirber Ul'"c,unt«b press nor aoUthN' ~a.n ec liable tor ;my loss Gf proHt or ::my other .c:<:Jmmercial c:bIT.l:lHCS, iDC"luGing but OOf limi~ [I) spee-~ n I. l"dodcnt;J.l. ~ooS(!ql!lt';:.J1tiaL, (10'1'" other O;ll't);;"jgC1,

T L<~.k!i'ni"ltt8: ;\H brand names and pi""CKJtJt:t 1lIlif['J~j used iii. thj~ book <Ire trademarks, registered Iribl::htmu.tk~, err .i'lldi: names of !h(;ir respective botdcrs. Dreamrecb PI\."Ss is niJl assccimed with uny prodm::'.l Or .... -eodcr IIknticmed in this book.

ISBN: 10-8 j·ln,·gjj·2 11-978-81-7111-355-7

U rheberrcc htl lch gesc h utztes M ateri a

CONTENTS

Need of f'l.J<;Ql, _ •. ,

ChallU!r 1 • Introdllction to plJsQI. :: -r .' ·,::·f;.· '. 1

_____ 2

Whot is PIJSQLI,.,.,.

Veo-,ion< of PL!5QL __ .. __ ._ .. .. .. .. __ .. __ .... _ .. .. . . __ ....

" ••• ,4

feature, of PLlSQL ,., ... ,.,." ".,.,.,., .... ,.,.,.,.

PL!5QL Block _ .. __ .. .. __ .. _ .... _ ...

____ .. -._0

. 6

.. __ .. __ .... __ .. .. .. __ .. __ ... 7

Pli5QL Co"t",1 SUuClure, ."" .. "... . .. .. __ .. __ .. .. . __ .. 7

U,;ng SQl wit~in PLlSQl _ .. .. __ .. . .. __ .. .. __ .. .. ."_.,, " 7

PLISO L Collections ...

8

, .. " ... " ... "R

PLlSQL Records .. ", ..

__ ...... , ..... 8

PLlSQl Suh prOll" ""

,, 8

PLlSql Paclage< .. __ .. .. __ .. .. .... .... _ ..

10

-,

. .. __ .-."" " , ,11

New Femur,,", added in PlISQL foc Oracle 1O~ .. __ .. -. __ ..

.9

PLISOL Arch hecture in Orac le __

Np mcd 610'-":5

'2

Kj ofB of Bloch

21

Ai\[).nyrn(:IIJS Blocks ...... " .. ", ... " .... ,._"

.. __ .. __ .. .. __ .. 21

Nffilecl Bloch ..

!otrod'udng DalaIYF'" ... , .... ,., ...... ,.,.,.,. ,,, ... ,., ...... ,., ..... , ..

___________ 22

Num'bcr Types. _ ...... _._ ._._" _ ..

__ 22

. __ __ .. .. __ _ _ . .. :27

_" .. ,, .... 26

Character and String Typ~5 . __ .. n ... __ . __ ,,_m", ..

Boote .. ~ TYflL"So .•• ", •• " _.

" .... .24

LOB Types " .. ", .. " , , .

Date, Tfme, and Il'It.f;!r'1o'-,al TypoC;.

v

U rhcberrec htl lch gcsc h utztes M aleri"

Working whh Dccfnrartors

._ .. __ .. ,.,., ,., ,.,., ,.,.,.,."".,.,.,37

UsifiB DEFAULT value

" .. , ..... 37

U~illH NOT NULL Cons.trilinl

" ... , .... ,ll

US;Jl g AI lases.

" .. " ... " 36

Intf()dllcing OncroCiJon;.,

."",,_ .. 38

Ass ignmenl Oper ,'''or .. , .18

Nitnll-.elk: Opet'd.tcJr-s .• _.... . .. __ ... __ .. ... __ .. .. __ .. .. __ .. __ ... _ _ ... _ ... . .. _ ... __ ... _ ... _ .... _ .. 39

logiGJI OPCri3l0.r5,m"m"m" .. , .. .. __ ... __ .. .. .. __ ... __ .. __ __ .. .. __ .. . . .. m __ • 39

Comp~tis.on Opcr~IO'S .. .. .. __ .. . . .. .. .. . .. __ .. .. .. . .. .. __ _ .. ._ _. 40

I.? NULL 9.pcJi3t.or _ _ _. _ .. " , , , , , , , ,.... , , , , .. 40

Ccncatcnntlnn Operator __ .. .. __ ... __ ... _ ...••...••..••

" ... , ..• 0

LIKE Oper~lDf" ... " ••• " ... , ...

, .. " .. 40

R, "go Opera ten BETWfE N ... " ..

_ .. __ ." ••. ,_.41

Li-Sl Op~r.j)tur: IN .,m"m", .. " ... , __ .. __ ... __ .. ._. __ ... __ .. __ .. __ ... __ .. __ .... __ .. ._ •.. __ ... __ .. .. .. .. __ . 41

IfuroduCi~',g A1Ifi~)liJr,'S _ ... _._ .. _._._._ .. ... _ __ . . ,._._._,_ ... _ .. _. __ • , ••••••• , •••••• ,.42

US'ing l:he % TYVr; Allribule __ ... __ .. .. . __ .. __ ... __ .. .. __ .. ..• _. _ .. ,42

~~i.~E thy.%_R.O~P~.~·~tri~ulc_,_.. __ .. __ ... __ . .. __ ... _ ... . .. .. __ .. __ ... __ .. __ .. .43

InirOOuciog PUSQL E'p"",;ons .... _., ... , _4J

Boolea n Ari.hrn~ i c Exoresslons

, •• ,4)

Boolean Character EJC"pres-sioll"5._" .. "

_________________________________ 4,'

Bool"(!'.an Dale Expr,('S5iQnS ., ... ,... .. ... __ .. . .. _ .. __ ... __ .. _ ... .41

DJ1,.WmC5c:onvCf~ion in P~QL . __ ._._._._._. ._._._. __ ._._._._._. ._._._._._ .. ._._. ._._. A5

,45

Implkil Cnnverslon ...

,45

Summarv .,.,.,.,., ..... ".,

_._ ... _._._._. __ .... _._ .. .46

_4f-1

,"

II

I OWE R j'l [Jd ! 'PPFR ·F. I ncr iens

I TRIM (mc! rURtM il'VClioui;.

R EPI ,'\C E E. lor' ii1tl

. ')7

!'is

;9

" •• " •• ,.1i:9

TO CHAR Fl,lnctinfl .. , ••

, ••• (,0

;\DD MONTHS Fllodion ..... _ __ .. _ _ __ ..• .. __ _ __ .. __ _ __ _ _, 61

MONTHS BffilvnN ftJIlc.tiof"'l __ .. __ _ __ ... _ ... __ .. _ ... __ ... _ ... _ ... __ ... _ ... __ _ _ ... _ __ __ _ : 62

I AS! DAY [! lor! jon

61

vi

Contents

N EXT DAY 'Fll nction

" .. " ... ..M ......... ..M

..•. ..b5

.....•. ..It£> .......... ..hli

.......................... ..JiZ

.... ..ftf5 . . .JiB

.... ..69

. .. ..lll

ABS Function

CF II jjI nd FlOOR FI'lfictione

ffl\NFB' F,IIVriinv

ROI J N D ELlO(tiQO

SQRT Function n ..

MOP ft 1 odjoo

("!..O'"'-""LJ"'NTiJ'·_jF:c-L1 .. nLJa-"'jQ'"nL......~~~~~_~ ... __ .. __ ... __ ... __ . . __ .. __ ._ .. _.

S.L JM MIOC[jon

" ... ..LJ

"'51 .. G"'NLF,,'w!r,_crwiO.llnL......~~~~~~~~ .. __ .. __ ... . ... __ .. .. __ ... .. ... __ .. . . __ . ..ll

......... .2l

................ "...1J

" .. " .. " . ...ll

[oovers, on E! 1 net jons

',_Q"--",N",y",-,F,,,RT.L..J:.fIUlIQf,,- ·",H"rlDLL~~~~~~~ ... _ ... __ .. . __ ... . __ .. __ ... _ •.

T.cQ".--,N""U,.'",M!CB",E"R-,-F",Lin("""-H",,,,,,-,_.~~~~ __ .

,,1 O ... -"'R_.F.J,JII.LL0cwl ... ioo..._.,s .•.•.•.••.•.•.•.•. _ ...•.•.•.••••.•.•.•• _ •.•.•.•. _ ... _ .•.•.•. ..25

REI! [N AM[ [I I tKtjou

..•....••... .....15

" "...Zli

fMPT~1 BLOB an(-lEMPTY (taB FLlncJi()n!>. ..••...••. __ •.. _ •...••

Misce!lancol!S fllnerjons J2

GREATEST a oC'! I EAST VI Detinn;;

! lSfR FInd! no F-Imcljoos

Summary .

Chapter 4 • Undl!rstandlng ~~~nb!O! Strudllres .' .- : . 81

D~scribins PllSQL Control StnJC1U~ _._.. ._._._._ .. _ _ ..B2

Usin_B Condt!jonal Control S!_.)t~ments. .. __ ._. ._ . _ ._. .. ...8.3

I F~ TH E N Statement

" .. .1I.l

.................... ..M

.......... ....Il.!i ... .llli

. .88

IF-THFN-_FI SF SIrl.emcnt

Using CA.S E S!.ll(.:omenl.s

Us. ng Sequent i-al Control Stalem ~n[~ .

GOW5tJtemen t

.••..• ..ll.9.

NI I! I St;11cmrnl . _ •. ....9..0.

lJ,i ng looping Cnnw1.I< I, in PUSQL .9J

I OOpSI,;".ement __ .. _ ...9J

fOR T nor SliUcm",nt . .. . .. .. . . .. .n __ ••• • • __ ••• n •• • • .lt3:

WHll EI oap Statement .. __ .. . . __ .... __ ... __ ... _ ... . .. . .. __ ... . ...... . ...9..:5

''''u"m'''m='ry'-'-'===== ... ''' .. ''' .. " ... ''' .. ''' .. " ... ''' .. = ... .. __ .. . __ ... _._. .. __ . ... ._. ._.

Chapt~ 5 • Implementing SQL Operations In PUSQL "7

Work, og with D Dl 'n d DMl St,remon" in F'lISQ L ..9.B

Lo_J'",i","S,_'",-:h-=o-,CccR=EA",T",E",'",'"'",'"",=c",n!=. ===="CC"'CC""''''cc''",.--cc''",---'. - .... -- .. --- .. -- .. --- •.• -- .• __ .. __ ... __ .. . __ ....9..8.

U5ing [he INSERT statement ... __ .. .. __ .. ... __ .. __ ... __ .. .. .. __ ... __ ... __ .. .. __ .. .. . .. __ .. __ $

vii

U rheberrec htl ich gesc h utztes M a\eria

Usi.-.,g [he SE.l'ECT surernem ",.,',.

,.99

U~ing the UPDATE. s:tal~lTIen[n"n

, 100

U~ing the- DE L ETE sl;:tlt'mllnl, n" on

, 100

. .. . .. __ .. ,101

________________________ 101

Using_ t_~e ~a~~MIT_~_Lille~_e_~l . .. __ .. __ ., .. __ .. __ ... __ .. _ ••

102

Using the ROll SAC K statement .. " .. " ... , ... " ..

104

Using the SA V EPO I NT 1.lalemen I .... ,' n.".,

___ .. 105

U, in~ Ih" ,ET TRAN~ACTIO N suuemern .. __ .. __ .. .. .. __ .. __ .. ...... __

_ .. .. __ 105

Us lnli!: ihe LOO< T ,1\Bl£ sLa[emenl ••• ,' ••• , ••• , ••• " ••

, .. ,106

Sun1ma"".,.,.,.,.,._ ... , ...

________ .... __ lO7

rI __ -- r.::.:-:_:.::.:-: ~:::..:'- ..... --'.::.::-3·,:

Working with PUSQL Collections .. .... n .. .. n __ n ... n .l1 0

SeJccling pUSO~ CollcrliGll Tvpes _ .. __ .. .. __ .. __ ... __ .. __ .. .. __ .. __ ... __ . .. .. __ .. __ .. .. __ .. .. __ . 110

Ddinins CO[lcClioll Tvp~ in PlfSQL . .. __ .. __ .. .. __ . . .. . .. __ .. . .. __ .. .. __ .. • I ~ 1

OccJarins C_nll'~qiOfl,V.ui.1bfes, . . .. . . . ._..... . , 114

I nil ta Ii efnn Col fectlons n.

,115

ReTE.fencing Cellecrlons ." ..

, 116

, 117

Comp.[Lr'ing Collections __ . .. __ .. . __ .. . .. __ .. __ .. .. __ .. __ . . . .

_ .. __ .. 118

Usin@ Co'll!Xtion ..... 1c:thods _,., __ ... _.,. __ ., . . . , . , . .. __ .. .. . .. _ .. , . .. . 121

Working with PI)SQL RQcord, n n n n ••• ._-128

I)cfining and DfflilIinq Records. .. __ . . . __ . .. .. __ .. . . .. . . . . 129

Assl,FJ.r1ing V.jJlucs to Rccords. ... " ... ,... ".",n."n,n"m, 130

Ins.er1h~& R-ecorrn: li"IlO the D;\I~b.a~ , ••• , ••• , ••• " ••• ,... 131

UP,L1Iin:g II Databaso ~'1i!h iR~m{J V.lllles. ._ __ _ _ __ _ _ _ _ __ .. _ _ _ __ _ .. 1.32

,"""nary " ,,, " , 133

Und~nil.1nding Implicil Cursors ._ ._._._._._._._. _._._._. ,_._ ._._._._._._. _. ._._ 't 36

ttmuanons of Implic;il CL~I"SQr's .. __ .. __ .. . __ ... __ .. __ ... _ ... __ .. __ .. _ ... _ ... __ .. .. __ .. _ •.

___ .. lJ7

Working with bplici, Cursors " ,

.......... 1]8

De-c:,laririg Explicil Cursors •• " •• " ••• , ••• " •• " ••• , ••• Opcni I'Lg [;.;1)1 ici I Cu !'Sor _. _._ .. n· _._ •. _n.· __ •· .. ··_n

.. " .. " 138

.... " , 139

___________________ .. -" __ 139

" 1'0

.. __ ... . __ ... __ .. __ .. .. __ .. __ .. .. _ ... _ .. , .. __ .. __ ... __ .. __ .. __ .. .. __ .. 141

Implici. Cursor AlldbuU~5- , .. "n ,n"n" ... ,m"n" ... "n"n 14&

Cursor FOR loop __ '" __ -' .. n __ 146

Cursor hpresl);ion-s _ ... _,_, ._._._._._ ..... __ ._._._._._._._._._ ..

.. 155

viii

U rbcborrec hthc h gesc h lillle,;!vI erla

Content,

Sf! fer fOR 1 IPDATE in 0 'NON

Su_mmary .

____ ._._. . __ ._._ •• ,1';:;9

Ovcrvi OW of PUSQ L Subprogram' .... , ... ,.,._

, -._.-, _._._ ... 162

f'USQL Procedures . .n ••••• _ ••• _._ •• _ •• __ •• •• __ •• __ ._. __ n •• __ "'_."

, •• ,', ••• '162

PUSQL Puncuons..

... " ... 164

wo rklnn with Subprosr.1m:;. P"'~t.1melc~£ ,

, ,." 167

TYJ?eS or Subprogram PammC!ICfS _, .• _ ..••. , _

" .. I&?

Us.i ng Ncratlcn for ,S-uhprcrg,HI m P,ua meters. . _ __ ., , ..

" ...... 168

.,, __ ,1611

Usi ng Su bprogr!!lm AI ii!Jsing _,

.. __ 171

Overl();)cling Subprngr~m ", ", " ".

""",, __ 173

Resincnon while ,apr Iyi ng Ove:r IOo1di ns

.. 174

Us i ng Recursio n WI th Subprogr.]ms

__ " ", 175

U'inB AUTHID Clause "

__ ,_, . . ._._._. __ ._ .... ,., .... -.,.,-..,.".176

Limitations of Scbprograms:

Summary ... ,.,.,.,., .. ,.,.,.,.,., .. , ".,.,.,.,,_ ...... ,.,.,"

, __ In

""" 177

Overview of PUSQl Packages __ " __ ." .. .. .. __ " __ 180

Package Specification and P"d.g,o Body .. __ .. __ .. .. .... " _ .. __ " .. " " .. ". ".160

Advantages of Package, " "............. __ 1 ~2

Und."",ndiog PUSQL Pacbge, wi!h Oracle "......... .., 183

The STANDARD Package .. .. .. "" ..

The DBMS_PIPE Package.

The UTL_FILE Pad<.S" , __

Ttle UTLHTTP Package ... " __ .. .. .. .. __ .. .. __

The D BMS_>QL Pack.so .. .. .. __ .. __ .. .

lB5 ,165

_ 186

lB6 lS7

Nali,ve Dynamic SQt \'5_ DBMS.~SQL Package

,168

The DBMS_j>.LERT Pockage.. .. .. __ .. . .,

189

U,ing PUSQL Packages .......... , ..... -, ,, '" " .. -..

The DBMS_>QL Pock.ge __ " The OHMS PIPE r.ckag e., ",."."",.."

,,, 190

" 190

___ .. .. __ .. __ .. __ .. .. __ .. .. .. 193

C~e,)Hng. and Rf..-movirig P~pc"S .... _ •.. _... . .. . n __ ••• n •• __ •• •• • • __ • • t93-

Sending and Re,ding Me>"'ge<" _ __ . . .. _,,_ .. ,... ",., 1:95

Th. UTUILE ,p.d<.ge .. __ .. . " "" .,.. 1,97

The lITL_,HTTP Package " ",_ .. .. __ .. .. .. ... .. __ . __ .... .. .. , 9~

Tim DBMS ALERT r.tkagc "" .. " ....... ".. .. __ .. __ .. .. .. .. .. __ .. ... __ , 200

Building vour own P.Jckage _ .

.. , _20J

Summary

,,, ,, 206

ix

U rheberrcc htl ich gesc h utztes Materia

TYI>5 nf Trig-gers. ,." ••• ,.,.,. ",.,., •••• , ••• ,.,.,. ",.,.,.,." ••••• ,.,.,.,.,., •••••••••• ,.,.,.

,.,208

1)i\lIL T(i'gge~~ , ... " .. " ... ,', .. ,', .. " ..

, .. 2D6

DDt Triggers .. _ _ .. __ .. .. ._ .. _ _ .. .. __ _ __ __ .. __ __ _ __ .. .. .. __ 211

D.ltabasc EV4JJlt Tri~,:E:.crs- ... ,... , .. 21 Z

1 ...... ::nEAO O.F Tri.gfjPfS .. _._,._ •• , 00 2·t4

AfTER SUSPEND Tri~mcr!io .. __ ... __ _ __ _. __ ._ .... _ .... _ .... _, ... _ __ ., __ .. .. __ ... __ .. _ •. .. ,_ ... .• :21iJ,

M,linl.aining Triggcr~ _._ .. _ _._._. _ _ .. _._._ .. _._._. __ ._ _._._. ._._._._ _._._._._. 21 i

fnJ.bling cr Dtsabllng Trigg.Cfi._. , __ .,_ •• " ••• , ••• __ ,_ •. , __ .,.... . ._ 2·17

Drupping ·rriggers ., " .. ,', .. "... " .. " .. " " .. ,",.. , , 2 T8

Ren .... ll1inJ.!; T:riMep"s." ••• " •• ", •• "... , ••• , ••• " ••• " ••• " •• " ••• , •• ,', •• " •• ,",.. , ••• , •••• ," 2. 19

Hai1dlinr, '\UIOTIlomr.u._lS T'!lnsa(tio:i1:) us,ing Trisgers. .. ,.,.,., •.• " , , •.• ,.,., .. ,., 219

Summary ._._. _._._ ._. _._._ _._._._._ .. _._._._._ _._._._._ .. _._._._ _._._._ _._._._._.223

. _' .; .. l:IIMikig UCf!plions in PUSQL -,. -.' 225

U n dcestandl ns PLiSQL E xccpr ions

........ 226

Ifl-El.IilL 'I:)(ccptiom . .. __ ... _ ... __ .. _._ .. ... __ .. __ ... __ .. __ . • _.,. __ .. .. __ .. .. .. .. __ .. .. __ .. __ 22iJ,

U,;e-r-lJefincd E....:ceplions, ........ , .... , .... , .... ,... ..00'.00'.'''_.' •• '' •• , ... 2]D

RilisiriS fxceptions In J:!USQ,l ,.,.".,.,.,.,., ,.,., , ".,.,.,." ,., , ,.,.,., ,.,.,.,., .. , 231

TI~(i RA'ISLA!} P'lI CAliON _E ~ RO R Procedure , ••• " ••

, ... " ... " ... , .... , .. ", .. " ... , ... " .. ",.,2JJ

H;lndling PUSQL hcep1iollS ._._._._., .,_._._._._ .... _._._ ... _.00 .•• _

" 234

H'in'"fllin~ [-..::ct.·plill')[ls Ralsed in Decl.lr';l!ion-s. "l3S

HiUldl i il~ b c.cpl~or'S R,a,l5:C{1 in 'l-tand ICHi.. " •• ,', •• ,' 2 36

U,ing SQlCODE and SQlER~M. .. 2JB

...... , .23-9

, 139

Summary

r:,~""=;"~

.................... 242

... 141

Dt:'Crilri~~ .1fid IniLializil1R Objcc' T,pcs n.m .. m .. n .. n ... n .. nnn ... _ ... n ... nnm .. m .• _.0000 .. 00 .. 00 ':iI4J

Usrng methods in Object Type-s .. " .. " .. " ... ".. , .. " .. 245

Mafl:ipul!i.1ing Ob.lt..>(1 TypW .00 .. _ ••. , ...... " ... , , .. _, .. ~49

illI1(>fil.:linc.e in PI 150.1 ' .... n.".' ".,.,., •• , ... , •.• ,.,. , ... , ... ,.,.,., .. ,.,.,.,., ........ ,.,.,.

,,25-2

1\1~.h_Qd q",crr_tding _nnnm_.n_.nn._n._n.nnn.n_. nnn._mnn:_254

I'liSQL (01100';0'" .1nd Ol>j"C! Type. ......nm.n .••••••• nn .•••••• n •• :156

U('linrns. SOL T\'pcs C'quivJlont Lo 11USQl Collectlon Types _156

US-UiS PUSQL Collt.:.clion.~ with SOL Object TvptlS: , ... , ... , ... " ... ,... , .. " .. 258

')',')

Urheb~rrel:htllch gesl;;:llutztes r..'fale-ri~l

Da'i:1base management ls 've,ry cruclal and tedious work for every organization 115 databases ~ contain, all important iniormation's of an organization, Oracle is a database used in almost every organization for managing data. oracle is a flexible database that eases the problem of "wMging data stored within, your system or on Oracle server. Now, Ihe question arises that how Oracle mimages the dahl. The answer for thls '1"estiol1 is PL/SQl, which is used for managing the database, PUSQL is, aver)" eflident and easier \0 learn database programming language designed to manage database, Each Oracle version comes with its corresponding version of PUSQL PIJSQL is" procerhiral dam base programming language 1J>.1( extends the functionality of Structured Query L;mguage {SQI.) and uses them with in it, procedural sraiements. PUSQL uses SQ L 00 Lan d OM L sta ternents 10 perform ope ra I ions sue has crea ti ng, a lteri ng, del eti ng th e database. These am the basic operations required to manage a database, PUSQL executes SQL staternen Is within P USQl block, wh ic his the ba sic u ni I of PUSQ l. PlISQL i. a very flex i ble database programming language that supports the advanced prncedural programming concepts and elemen 15, sud> a 5:

Cl S upp 0 rt r or a II SQL d atatypes a 10 ng wi t hits PUSQl deli ned da ta Iype,. Use of con t rol SI!1!ernenrs (lr-ELS~-'l'H~N}. iterative structures (FO.R~LCQ?, \~HILE-LOOP).

o Support for subprograms such as procedure, and functions. triggers, cursors.

Cl Exc~ption h.lndling Ihat lei> you create bug free program and help> in mo,n"ging errors such

a, data not found,

SQL CJn issue only ;1 si ngl<1' statement at d time, which will become more lime consuming when need to execute many SQL statements and leads in low database performance but PUSQL allows you 10 send multiple SQl statement 10 database simultaneously awl thus reduce. the overhead of accessing the database for evert singlE:> SQL statement. In this. WLLYI there are lots. of advantages 01 u.ing Oracle'< PUSQL, 1.0 know those let's ~t~rl working with PLISQL,

To start working with PUSQl, you must need 10 know its need, advantages .. architecture, and features. This is all that we cover in this chapter.

What is Pl/SnL?

PtJSQL is procedural lang<J,1gc, which is available with Oracle, PUSQLis not a standalone langltag,e because it works with Oracle. II is an extension to the SQL (Structured query language, a do ta base la n guage u sed 10 perform vario us I un CT i ons su ch as q ueryi r.g "nd U fc.dati ng do ra, on a database), Pl, in rUSQL stands ior procedural language, PUSQL extends the funClionalit,. of SQl and then comb i nes it wi Ih proc od ura I fu n ct iona I i ty su c h as loops, procedu res, CU JWTS to P rev ide bener a nd more sa nsf ~ct(>ry resu It tha n SQ L,

Now, the question arlses Ihat lfwealready ha,ve SQL (a flexible and easy to use query limguage) then what is the need 10 extend the funcrlonalltv of SQL by PlISQL? You must be curious to know that why we need PUSQL and what are the reason, behind its success and in making it a ubiqultous database pr'ogromming t"'>gu'Jge~ Now, we wi II depict the nE%'<.J to develop PUSQL.

Nood of PI/SOL

A, we know SQL is a very easy and more convenient database query language bul besides thai it has some limitations Ihat become the need iOT developing PUSQL, In SQL, we hove 10 execute a jingle statement al J lime. 50, if we need 10 execute multiple statements then Oracle database

2

U rheberrec htl lch gC5C h utztes Iv! ateri a

cr,apler 1: ]nlro.J",ljon W PUSQL

must be c a lled several times to execute all the issued statements that reduce the database performance. To improve the database performance, PUSQL is developed. There was a problem with the security of database as the code is executed on cI lent-side rather than server, We Were not able to handle exceptions that lead in sudden termination 01 program at runtime,

To overcome all these problems, PLlSQL has been developed. PUSQL has lots of advantages that have made it a very successful and omnlprsssm database programming language thai is in wide use with Oracle, Here are given the advantages of PusQL:

CI Ea s i Iy ada ptable an d SQ L supporti n g CI En han ced Performa nee

a Portability

a Security

We will study all these advantages 01 Pl./SQL in the sequence. Let's start studying all these

advantages in delai I. •

Easily adaptable and SQL supporting

PUSQL supports the entire charactertsnc and statements avsilable in SQL such as select. insert, update, delete. Database can easllv be created and manipulated by incorporating the SQL statements in PUSQL bloc k.

PUSQL ,uppom all datatypes that are supported by SQL so you do om have ro convert SQL datatvpes in PUSQl datatypes, PUSQL also allows you 10 use SQL operators, functions, and '0 on.

PUSQL is easy to learn and understand as most of the rharactertsucs are extended from SQL and the synta ~ u sed In PUSQL I. very simp I e to learn <1 s it uses lot. of keyword. th" Idea rl y express the purpose of your code. Being iamiliar with any of the programming language such as c, c++ makes it easier to memorize and Use the Pl.!SQL programming syntax.

Enha nced Perform ance

PUSQL provides bette, performance than SQL because one SQL statement can be processed at a time hy ~data~base, which meansif you have to execute more than one SQL statement than you have to access database as much as SQL statement you need' to execute. Accessing the dOlabase several times ,,,,,,,lIS in the congestion in network as database are generally stored ~on server and thus the time to process SQL statement will automatically increased, which leads in low performance.

In PUSQL, more than one SQL statement can be sen! to Oracle database for processing because in PUSQL, you can collect all the statement, in PUSQL block which is the basic structure 01 PLlSQl andall the p'ograms in PliSQl can not be ere .. led without PUSQl block 01 you can also use PUSQL subprograms to collect multiple SQL statements. A subprogram is a PUSQL block thai consists the seqoence of statement, 10 perform some specific task. A subfJfOgr.lm can be (a II ed by other PUSQ L programs, Thus, 0 racle data base IV ill be accessed on I y once an d til ere will be no congestion in network, which results in the better performance. St"C the Fig, rUSQL· 1.1 to understand the working without using PUSQL and with using PUSQL.

3

U rheberrec htl lch gesc h utztes Iv! ate,i"

B~GIN

IF ..•• THEN

sal Statement ElSE SCL.,stalolTl.ol3nt END,IF:

END,

pt,lSQI", tJlQ~k with mlJlUipie SOl. $tal;$metJ.'I$

Fig.PUSQL-l.l

In Fig.P[JSQU.l, it is c'learly depleted that before the use or PUSQL, an application has 10 communicate with the database with several independent SQL statement, that ultimately leads in overhead on the database and reduces it' performance" while with the use of PUSQL, you are passing several SQL statements within single PUSQL blocks to database at same time and which SQL staternents has to be executed depends on the conditions provided within PIJSQI. block In this way, PllSQL in Oracle provides better performance.

Portability

PUSQl is " portable language; that is, program5 created in the Oracle environment can also be executed on on)' operating system thai supports Oracle, PUSQL programs follows Write once and run everywhere {within Oracle environment) slogan.

Security

PLlSQL provides higher security than SQL. PUSQL stored procedure> places the application code centr",lly on server rather than placing on client system. By plactng the apphcauon code cemrally, )'OU can hide the cod" from other users, You can set the permission to access PUSQL procedure by various users for perlmming different ac\iviliC5 such a5 updating, deleting a rable or data Within a table.

These are some advantages of PL/SQL due 'e which PLiSQLis a ubiquitous database programming ["ngu,lge. Let's have an overview of the various PUSQL versions to know the cnha nccrnent mad" in P [JSQ L version, rcl eased with every new Oracl e vers i on.

Versions of PVSaL

Till today various versions of PUSQL has been released along with the versions 01 Oracle. Every new version of Oracle comes wlth its own version of PUSQL and every new version comes wilh additional characteristics from previous version 10 provide you better funClionality. I" this book, we tire considering the Oracle 109 and the PUSQL version that is 10.0 thai hits been released wlth it. Table 1. .t depicts "lithe versions avai lable till the' release of O"'.cle 1 Og.

4

U rheberrcc htl ich gesc h utztes M aleri a

U rheberrcc htl ich gesc h utztes Mater

Now, we have discussed that how Oracle's PUSQL has been improving to provide better performance.

l.et'sstudv the features ol PlISQl to know all that PLISQL consist, ;md how it helps in making database programming easy and efficient. Here, we study these features, in brief because all features will be discussed in detai I further in this book We also discuss the new feature, included in the Pl.!SQL for Oracle lOS.

Features of PlISQL

Many of the key fe,1tures in Oracle 109 PlISQL are same a, the previous versions WUSQL 9,2), Still this version has some new ,improvements due to which the database performance is more enhanced, PUSQL has changed the wav of database programming and becomes the omnipresent database programming language.

PlISQL allows usi ng SQL statements within Pl.!SQL block. Program flow can be controlled and rnu I tip I e SQ L sta tern ents ca n be sen t to do ta base at t he same time. P USQ l subprogra rns Iproced"res and f'JrlCliOJ1SI can be used to make the p"'gram easler.

We \V i II dis c uss ,,:II lea fu res j n dew i I 5 j n fo rthcom in g c hapters bu t here we can have an overview of all the main features of I'LlSQL Jlong with the new feJtures added in thiS version of PlISQL in Oracle 109. Here we discuss Ihe following main feature" which are then followed bl' Ihe new ft!!l! u res added iii th i So vers [On;

o PUSQL Block

o PliSQI. variables Jnd constants OPUS Q L centro I structure,

o U,ing SQL within PUSQL

o PUSQl collections E:I PUSQl Reco rei,

o PLISQL Subprogram' Q PU5QL packages

Q Exception Hilndhng

I-I ere, we start di<cussing all these leilI ures,

pI/Sal Block

A PVSQL p">gram ,,}n,i>l' minimum one PlfSQL olock. II, i, nOI possible 10 creole" PtiSQL pros,"m without I'IJSQL block thai', why PlISQL block is very important ami basic unit of PUSQL A PLlSQL block has different pari'; and tha: paris are Declarative part where you declare item, sue h as type" vari a b I es: iii, opt io n J I po rt, E xecu led part where yo u wri te p rocedu ra I J nd 5QL statements and is necessary part of PlISQl block; without it Pl.!SQL block is incomplete, and fi",,1 part is Exception handling where you provide the code to handle exceptions: it is also an optional part

A PUSQL block has jour keywords, DLCLARE, BF:GH1., EXCE~TION. and END. DECL/\R!: keyword is ","'<:I to break the PlISQL block in declarative part, BEGIN is used to define the Execution part, EXCi>PT ION keyword is used to start the exception handling, and END keyword

6

U rheberrec htl lch gC5C h utztes M ateri"

1, I" Iroo "CI"m 10 PUSQL

is used (0 end (he PlJSQL block. See the following snipper to understand the PllSQL block strucfure:

Variilbles and Constants

PllSQL allows declaring vanables and COOSIJ~(S so that they con be used in execution part. Variables and constants must have to be declared before using in statements (Executjon part). Variables and constants can have any SQL (such as I!U~!BER, CHAR, YARCIIAR2) or PUSQL datatype (BOOLEAN)_ The only difference between the declaration of variables and constants is that while declaring constants, you need to use CONSTANT keyword and value should be assigned at the time of declaration. In case of variables, values can be assigned in execution part.

Control Structures

It is a very important leature of PllSQL tha: lets YOLI allow adding constraints on statements 10 sen d mu II i pie ,10 iemen IS to do ta base a 1 t he sa me I i me rather t han send in g the severs I independent statements as we ever did in SQL. PllSQL provides the following control structures:

CI Cnndl tional co nlrols: T hi, contra I a llows you 10 execute severa I SI a tern ems ba sed 0 n different condttlons. You can check those condition, with the help of I F-THEN-ELSE statement to execute the proper statement. If clause checks the condition and .if the condition is true' then the statement written under TI~E.N clause wi 1.1 be executed otherwise the control transfers 10 ELSE. clause and that will execute, In this way, conditional control structu re works.

IJ lterative (on trol s: Somer i ones yo u need 10 exec ute a seq uence 0 f 51a te OJ ems mull ip I e ti rnes, whi c h was not poss ibl c wi th SQ L but PUSQ L provi des you :i terative co ntro I, to complete your requirement. PllSQL provides you severo I loops such .15 LOOP---END ioor, FOR LOOP', WHILE LOOP. Allthese iterative structures wil,1 be explained in Chapter-4.

IJ Sequ entia I mnt rol: This control allows you to Ira nsfe r the con trol from one pari 0 I P rogr am to anothe r. PUS Q L use, GOTO keyword 10 su P portseq ue ntia I. co ntro I.

within PI/SOl

has extended a II I'll e f ea lures of SQL. It a II Ow! U, i ng a II SQ L data ype~, 0 pera tors, and '0 on, Using rllSQ'L. .11 the DDL and DML statements can be executed from within PUSQL block.

7

pI/Sal Collections

Like other progr.Jtllmil1g IfJngll.1gC:"5 such as. C1 [+4-; PLiSQL also allows you 10 groull elements of similar dat4..11yp(."S. ln c, C++, grOllp of elements 01 same datarype is done with the usc of arrays, hash table ,an·d so on, but here iJrr~ys are called JS varrtlys and hash table [He known as assoctatlve arrays. If l'QU arc fami I iar with In)1 other programming l"ngtlJge such JI C, C+ + then iellmiflg, PUSQl. collections become very easy but if you art: no! 'Jmihf:Lr with (lay other [)roW.1mrni r ~g I';rnw,u\gf~ .~I,i1d it 'i!; 1he :'jrSl 1.:H\gu;:-lg,e ~!OU are 51udyi Fig !ben. also h~vc no need to worry bCCiHHC PUSQl is an ~'asr langll~gl;' to understand. The lise of PUSQL collections wi]] be depicted in the Chaptcr-e ()f Ihi5 book.

PVSOl Reconfs

Records are like data structures. used 'in programming languages such a'S c, c++_ As data structures ;Ire used to group various r.=lemenLS Df diHeril"nt d;j).t~ltyp~S, in the same way records are used _ The on I y d i fie ren ce bel wee" co IJ eel ion, i' nd records 'i 5 I h;lI us i l1.g co II~~ I i ons yo" C,' n g!OlOP' clement of similar datatypc and using records dissimilar datatypcs wn be g,rouped. For example, if you want to collect Inc iniormation of ,)0 employee such as. his.lhc-r nome, ;:)g€', address. then you C;]rI do thi~ by u~ing a :sir.gle record hut if you use collection then you have to ri'l~ke V(lriolU.1j. co'lh-.'f.:liun tsucb (I~ V'~~n';;ly) to grour the elements of 'S-irnilar dalilype. The use ul I'USQL records will be depicted in the (h"pler-(, of this book.

pl/Sal Subprograms

PUSQL a lso allows li'Sing procedures and 'unctions as other progrtHnr:ning languages. ln f)IJSQL procedu cos and f II ncb ons are collect i vd), kn own as subprograms. 1\ P IJSQ L su bprogra m is sirni:ii1r to PL/SQL block (anonymous block), except Itl.!:"Lt a subprogram must have some name so I!l;:l! il can be invoked anyvl-1f!ere in the progr.:lll'l or in any other application

Subprograms JrC very important in I(']rg,c applicauon .J.S it breaks down the big and complex "ppl'ic arion into cilsi.ly managt·.ahlr~ modu los.

Subprograms have promoted the concept ut rcusabil ity. The same subprogram can be used more than one time in V.1tr:O'LIS applications. Once tested successlully then it can be used dircctl'y in ..; ny applr<,;a1:ion without \'vil'S~irlg tune (In \"lr~ili!':lg ~I ~Ig;llin ~.nfl ,18;1 in fur;t new appl icatloo.

PUSQL procedures and functions are structurally same but have only one difference in which" function 11" EETURN clause. SubpmgrJm' will explatn in .Ietail ;" Chaptcr-B of tlli, book.

pi/Sal Packages

A P1JSQl package is known as database object, which is used to bundle logicaily related PUSQL procedures and, (unctions. PIJ5Ql comes \·vilh, lots of pr~defi.Fied pack;tg(!s such ~1~ DEli'tS ---,~L~RT, [m:l$ _OUTPUT Ih,'1 C.1r\ be used: eli recily in you, .1ppl,icJlioll Or new packages with your O"'~11l specificauons which c.~n otso be crcntcd,

A PtlSQt pa(k(lg~ has two pr.lt5. ~pecifficalion and hod),. SJ1CCilk~l.~inn, P.1(t can be created with the I;,I$C or Cl'\:E,r~TE: ?n.CKAGE SQL statement Ilr,~d use to declare constants, variables, procedures, functions, cursors and exceptions in a package.

8

U rheberrec htl lch gC5C h utztes Iv! ateri"

1; Inlrod",.lio" 10

Package body is created with the use of OlEATE, PACKAGE BO[)Y, SQL statement and package body conta i ns p rocedur a I and SQ L sta temenis. Basic stru c t LIre to create PUSQ L package is given

This is just an overview of packages in PLl5QL. P;)ckages wi [I be expla ined in detail in Chapter-s of th is book.

ExcePtions are runlime errors that interrupt the execution of PUSQl pros,.m, There are many

such as program is not properly designed, dividing any number by Zero [oroccurrence of an exception. To avoid the pros,am interruption, PLlSQL provides the mechanism to handle the exception. To handle exceptions, enclose the program code within ,8EGIN and END dJUSC with except ion ha nd ler in P USQ L block. !;:XC 8 rn 0 N keyword ,i, u sed to s ta rt t he exceptio n h a ndl i ng in PLlSQ L block

PLlSQL a I so a [lows you to create your ow n ex cept io ns a long with ha n d lin g the p redef ned exceptions (tilis type of exception generally occur when any number is tried to be divided by zero, stack overflow and so on). Z!;:RO nrvr pc; exception will occur when you try to divide any

number by lero. -

To crea te your own except i ons, RA I S E: <to te m ent needs, to be used. H ow to hand I e exceptio ns an dhow to sene ra te you r Own excepti On wi II be exp I a i ned in Ch,)pter ·11; 0 r th i, book

With the end of preceding given feature, you must understand that why PUSQL is so POP" lor, 'now we continue with the new features added in PLlSQl for Oracle 109.

F8stures added in pI/Sal for Oroclc 109

features added in this version of PLlSQL have made it more convenient easier, and mom automatic to use. New feature, added in. this version are as [ollows:

a 1 mpro'ved Performance: Th i s vcrs i on of PUSQl co mes wi rh rrt I;) re au roma ted featu res SU ch as reuse the exp ress i on code, i rurod uctio n of new cia ta types for process i ng sci enti fie opera t ions wh i C h has involved in imp rovi ng its perform" nee.

CI Support lor FORALL statement: E'ORA.LL statement lets you allow to process OML statements more ef-ficiently b), iter~ting Over non-consecutive indexes. PUSQL has 1 NDI CI;;S or an d V 1\ LU C; 0 r clav ses to i te ra te over no n-<;OI1 secor ive indexes. E'O RI\ LL statement U Se5 specified index in a collection to iterate and process the statements,

9

o Inlroducing IIINARY _FLOAT and IIINARY _DOUBLE floating poinl datatypes: TllOSO are two n "I\' ; ntrodu CI ions in the da I" types, T h cse do tatypes ,\J pport IEEE 7 S 4 fo rmat a nd are of floaling polnt Iype_ These are used lor intensive 'scientific cornputauon where floating datatypes are used in calculation.

o Enhanced O~erloading: OverlO<Jding has improved in this version. Subprogram' that hove d i Heren t nu merle data types n s pa r i:1 meter can be ove rl oaded in. t h i 5 versio n,

o Improved Nested Tables: Now you have more enh,\r1Cf.'(1 Nested tables. Uling thi, version, nested tables can be compared for equality such as you can check thai whether a nested table is a subset of another nested table or not, you can check whether ~ paflic"I;lr element is a member of a specific nested table or not.

o Compile Time warnings: These femures helps in making a PUSQL program more robust and w,,11 funclioning, By using this feature, Oracle issues warning, during I'USQl program compilation when found any problem such as passing char value to float column in LNSER'r statement. You can use PLSQl._l'ii'lR)JHIGS iOiliJlil<llion parameter and DBi'iS_ro'l.I<R!HNG pac:ka,ge to manage' compile lime w·amiflg~.

!J Implicit conversion between CLOB and NCLOB: Bdore introduction of Ihis ie<llure, user have 10 Lise- ro CLO g and ro NCLOB to convert CLOS into NeLCS and NeWB into CLOE bUI now user do nol have to conv('fi II1l'm explicilly because in this version, Oracle makes implicit conversion between them wherever required.

!J Flashback. Qu~ry Functions: This ieature is used 1<1 know the tirnestarop associated with a particu I a r seN (5 ystem ella nge N u mber) J n d a I so SOl J I particu I a r momen I of ti me a rld for this. purpose, you h(H:e SCN_TO_Tl!'1EST!~N~ and TIMEST;\l.'j~_ro_SCN functions to use. sen '1'0 'rIMES'l'_~l'j ~ function takes. SC'N number .[IS parameter and returns rhe timestamp as.soci~te(1 with that seN while 'TI['.rEST_~.1'!rP TO sen lunction lakes lime value ~~ par" meier and retur ns Ihe seN al IiMI mome 1\1. _ _

Here, we have completed discussion on PUSQl feature, Joel the new features added in the PUSQL ior Oracle 10g_

Let's study the baslc working structure of PUSQl in Oracle. We are talking about the archlierture of PI1SQl in Oracle, II is net:e,,",y to understand IIIe architecture become if you do not know t ha I how P LJ5Q I. process the Sl;) remen IS inc I u ded in r iJSQ I. block, i I becomes d i fficu II 10 understand the PUSQl prol>romming,

PUSOL Architecture in Oracle

Architecture of PUSQL represents it. basi" working in coordlnaticn with Oracle, A. PUSQL block CJr subprogram consists of both procedural starcments and SQI. statcmeots. PIJSQI. archirectvre describes the process ih a I how PUSQl in 0 ra cI C interprets" PUSQl b toe k or subprogra rns PUSQL architecture in Oracle 109 consists of PUSQL block or subprogram, PlISQl engine, and Oracle server, PUSQL engine compiles and executes the PUSQL block Or subprogram. Oracle database or application development tools such as Oracle form" Oracle rep oris contains PU'SQl engine. PLISQL engine contains PUSQt procedural. statement executor 10 execute procedural statements within 11 PLISQL block or subprogram and Oracle server contains SQL statement exec utor to execu tc SQ L still cmen IS_ PI.iSQI. e ngi nc and 0 racl e server wo rk in co- ordi nan 0 n 10 proce,s <1 I'USQL block or subprogram. f'igYIJSQl-1.2 depicts thJI how I'USQL engin~ and 0", r I e server work mgetlwr an d pIOU><;S a PlISQL bloc k 0, subprogra m.

10

U rheberrec htl lch gC5C h utztes Iv! ateri a

Chn,,'cr J ·/,J/md<lcli<m 10 PUSQL

aEGIN Proe&dtJral St8temen'lS PlISQL Engine
If .... THEN
SOL Slaternent I
ELSE Ptocedor.' I
SOlStalel'llenl SQLStatemen~ Statement
END IF: Executor
Elm: PUSal61od<

Oracle Server

SOL Steternenl E._::(13CUtor

Fig.PUSQl.l.2

PlISQl engine accept> procedural statements and SQl statements as input. PUSQL engine then process all procedural statements through procedural statement executor and send the SQl statements to Oracle database server to process. In this way, a PL/SQl block 0' subprogram is processed.

With this, we have completed discussion on PUSQl Architecture and the wai' a PUSQL block or su bprogra m processed.

With the end of discussion on PUSQl architecture, we finish this chapter. By now, you must have enough idea "bout PUSQL such "5 the requirement of PUSQL and it> architecture. Before dosing this chapter, let's have" glance on summary.

Summary

In this chapter, we have studied about:

IJ The introduction of PLlSQL

(J The Need and advantages of PLfSQL IJ The various versions of PUSQL

[J Features 01 the PUSQL

[J The PUSQl Architecture

11

Urhcbcrrechtlich qeschutztes ~lalcria

Urho!le"achll,eh geschoilzlOS Bild

I, 'n the world oj' computerizetion, when we talk about progr~ms, then we must also lake into consideration concepts, su.ch .:15 the ptogram structure and datatype . .A program may contain WHiOLJI varrables 1,0 store dJla and those variable, must be assignru wtth some specific dararvpes Thus. daraiypes can be defined as " formal to store data, PL/SQL provides various daWI.ype" such ~\ l lj'!'EGEIl, Fin,., r that hdp Oracle to (home a ,to rag" formal for internal representation of objects and lrnpose [1 rdngc of values UpDr1 those objects. A rUSQL developer sh 0 "I d' have know ledg(' of th e prcdef ned da I" types a ssocla led wi I h P USQ l so In JI one can choose appropriate datatype for iI variable "sed in an application . For example, you Can choose PliSQL data type w, RC HAR 2 lor nil", e of ,r h u rna n bei ng. Further know I edge 0; the basic program structure of P.lJSQL also helps us ln p~Htitjoning Ihe application into easily rmm.ageable sections. Th i s p41 rt it ion i n g a lso helps us to ca tch .[l nd fix [laws in. d iffere III parts of the progro rn, We begin rhls chapter with a discussion on Ihe PlISQl block structure moving on to further concepts, such as datatypes, lexical units, and operators whose prior krlO'L>\rledge is eS'SeiHii1:1

before begi'ming, with PIJSQL -

Describing Block Structure

PUSQL is also known as a block-structured language as a simple PUSQl program contains many logical blocks where each block solves a pari of the problem. For example, a PUSQL program may use any hmction i""'d(, 'Iself to perform some operation and thiS 1'"n(;I.io" then helps in solving some pan of the problem, which is to be addressed b), the same PLJ'SQL program.

To understand the functlonlng of a PUSQl program, we divide its study into blocks and study each block 'Sf~p,M~I,ely. Every prograrn consists of one Of' more blocks .. where each block contains related declarations and statements. A PUSQL block cao consist of the following sectionsin Ihis seqoence.

Cl Block Header

[J Ded" rat i on Sect io n

Cl E:"';<;''C'Jliorl Sectlon

Cl Excepl ion Sect i on

Block Header

The block header section con lain, the name of the block. It is optional and used only when there is .1 need to assign any name to a PIJSQL program, Name a,sign"d to a PIJSQL progr.lm helps in calling it in other PliSQl programs, The rllSQL block header in PliSQL block structure i, shown in fig.f'USQl-2.1.

I fiA'!!7"';(l['J $:t;tj:1jI. ]

P-o.:O

14

U rheberrcc htl lch gcsc h utztes M ateri"

After the block header. we need to declare PUSQL variables (which are further used in a PLlSQL execution section) in the declaration section.

Declaration Section

We now need to put inlormationin a program block about the variables used in the block, such as associating datatvpes with variables,initializing variables. This objective is achieved using the declaration section. However, rhls section is not compulsory. It is used in a block only when we need to declare variable s. II a 'Situation arises where we do nol need variables, this section can be avoided.

The declaration section starts with the DE:CLARE keyword. After the DECLARE keyword, declarations of variable, are provided.

Th e syntax for wri ti ng (h i s block is as fo If ows:

The execution section follow, the declaration section.

Execution Section

Execution section follows the declaration section in the conventional program block, Execution section i I the most i m porta nt sect i on of the PUSQl block ~I ru ct ure as it;, responsl b I e for the actual execution of the code. In other words, we can lay that it is the functional part of the PUSQL block.

Tn; 5 sectio n sta rts with the BE:G I N keyword a nd ends wit h the EN D keywo rd. B etween BEG I N and END keywordsl we write the set of instrucucns or code Ihat we want to execute uSing rUSQL.

tt is however not nece5Sary that the code we wri te in t hi, sect i on must produ ce an act,i on. The code gets compiled even il the lnstructions sive~ in the execution section do not signify"n action.

All DMl (Dnta Manipul"tion language) and DDlID"t" Definition language) commands may be used in this section. Listing 2.1 contalns In example of the execution section of the PUSQL block.

listing 2.1: Example of PUSQL block containing execution section

listing 2.1 shows the code to retrieve the system date into a variable {v~datG_tirn8) of type DATE.

To retrieve the dale, we use SYSDilTE (In-Built PUSQl function).

15

To di'ploY the output, we use ~UT_LINE procedure of DBt~S_OUTPUT lin-Buill PUSQL packagej,

To dispkly the 'e5lJli. we use SET SE:RVERQU'['PUT ON because by delauh SQL "Plus does not read wh,'t .J PUSQL pl'Ograrn has written with DllMS _OUTPUT package. We discuss more abo lit I h esc co ncep I; lu rther in the book.

Listing 2,1 call be executed in the lollowing two ways: a Using SQL "Plus

a Using iSQL ·Plus

Let's explain each way in delail 10 execute a simple- PUSQL progr.tlnl_

Using SOL' Plus

II is used to execui C I he I' USQ l P 'ogram, and ,t a re men ts on J sl ngl e user mode, t hal is Oracl c PUSQL il151.)lled 0" a sysiem cannot be sharedhv multiple users.

Let's see how 10 execute Listing 2.1 ill SQL 1'1",. To execute the li'lin~, follow tho step' g'iven here;

1. Click start-s All Programs~Orade-OraDb10g_)lOmel~Applic-atioT\ Devel0l'n1ent~SQL I'lu s. as shown in l'ig_PIJSQL-2L

U mcberrec ht len gas G h Crtz tes 8 i Id

,; g.I'lJSQ 1.-2.1

The log On window appears, as shown in Fig.Pl/SQL-2,3.

16

2. In the Log On window, enter the user

Fig. PI.ISQl-2. 3.

J. Now, enter til e password as tiger in

4. Then, enter the host stri ng ; n th e Host

5. Now. click the OK button shown in Fig.PUSQL·2.4.

6. Now, write the code shown in Fig.PUSQl-2.4.

(c) 'i':!, 211l1li,

tel:

Patilllil'!ilP 11!11E.ntP'l'p:t'i'SE' ~Ii.~ pnHth.JI1I!J. Pol .. .'IIP II!'!'"

U:T UIU,IEIIC",.UJ IJI'4 DEa.i£lU

U'_d.ltlP_tllll!' Iilll!.i B{CrH

:5.UfU I I'll IJ

7. Now, press the ENTER key to output will be displayed as shown in

as scott in the User Name text box, os shown in

Password t ex t box (Fig. rUSQl- 2.3),

text box, as shown In Fjg.PUSQl-2.3,

-2.3). The Oracle SQL 'Plus window appears, ,15

2.1 in the Oracle SQL 'Plus window, as shown in

It,., ease HI.1 _'.2.111 - 1'''llIoillll(:t hili N_1 .. illl~ IIIp~i!,lll'llr,.

the code, A, soon <15 you press the ENTER key. the PUSQL-2.5.

11

U rheberrcc htl lch gesc h (jutes Mate,;"

Til i 5 Js (I", process to execute I h e P LlSQ l progra ms an d 51" Ierne n I., in SQ l "I'I us.

Using iSQL 'Plus Console

II is used to execute the rU5Q!_ prow""" and SQL statements 0" networked systems. Multiple u sers in the same netwo rk can access 0 racl e P USQ l installed 0 n a system bll spec i·fy; ng the network path (For example, he t.p : If Loca Inos t : 5560 I is'll pi us /).

i.ers follow the steps given here 1.0 execute Lilli"S 2.1 in iSQL 'Pl"s console:

1. Entes the URL (lor example, i1 top: / /1 cca Ihos t.: 5560!.i s'llplus) in the Address bar of yOL_lf web browser (Fig. PLISQL·1_61 to open the Oracle iSQl'Plus login consote (t' ig PtJSQt.. 2 _ 71

fig.PUSQt-1.6

2. Clid the Go button, as shown in fig.PUSQl-2.6. The iSQl"Plus login console appears ii' igYUSQl.2.7).

J. ln the iSQt.·PI", logi,n. console, enter the USCr name ,'S scott in the Usertl<lrnc (ext held, as shown in, Fi!:_PLlSQl·2,1.

4. Then, enter the password in the Password tex! iield IFig.PIJSQI_-2.7l.ln our case, we have used the default password that is tiger.

5. Enter the host 'tring th,'t is orcl in Connect ldentifier text lield. as shown in Fig.PUSQl,2.7.

6. Now. click the togin button {f;g.rUSQL·2.7:. The Oracle iSQL 'Plus workspace window appears, as shown in Fig_PUSQL·2.B_

18

U rheberrcc htl ich gcsc h (jutes M ateri a

O,opl" 2: rUSQL Essandsls

Fig-PUSQL.:!.7

7. Write the code w,i'neni'n Listing 2.1 in the workspace wi ndow and press the E.«ule button, as shown in fig.PllSQL"2.8.

FiC·PUSQL.:z.s

The Oracle iSQL 'Plus workspace appears once again to display the output, as shown in Fig-PUSQl-2.9.

19

U rheberrcc htl lch gesc h (jutes M ate,i a

WE

W-:r!o:ip:a:;.e

!IIIo !;;;I.. f'II6olI._l!lI:&. ......... 101 __

-,

!

~~m-Ji='!...4'~

~"t .... [:·· .. :~··lJKIilooill ... Li!;I"r ~Ilr.:0r:9::....rer..iIDr_1_.F>t'Fl"!ii:'oold'.o!; iF.K]:.r.v:P.ll~.J."''''",.,...,.Jio:'ol;

I-

L______ ~

~~(iI-;-~~

l~,jj\~'OO

F'1J':!:l...17~.Hi!J.I:,('!~<.:~II,o{_:lr.1)~I~

--.-- -.- ---~

F;g.PU5Q~-!;~

This is the process to execute the PUSQL programs using iSQL 'Plus console. Now, if you want to execute some mere programs then dick the Clear button, as shown in Fig_PUSQL-2_1 O.

This will' clear the workspace window (fig.rUSQL-2.10) and then you can. continue working _ with other PUSQL programs.

..

r J

r"jl~I'ltj::t'~,."'IoJ~"PII". "~j_1

r---·----·····-

20

U rhcberrec htlich gcsc h (jutes M ateri a

So, these are the two processes to execute the PLlSQL programs. Now, lei's continue our discussion with ihe nexll'LlSQL block structure ihat is excepnon section.

Section

Exceptions are certain abnormal conditions, which occur sometimes during execution of a PLlSQL program and cause the program 10 terminate. Exception section of the program block is an optional one. Alii secrlons of the program block except the execution section 0fe optional sections. To make a P.LlSQL program free from runtime errors Of exceptions. you .rcsuggested to use exception section in PU5QL programs.

The exception section in a block begins wuh the keyword EXC£~TION and ends with II,,, keyword EN D.

Th i S sect i on bas i ca lIy ca tches the errors that occu r wh en the program is execu led. These errors are c"ughl using the various funcncns provided specific.,II), fo.r this purpose. Some functions for exception handling are provided ,mder the STp.,NDARD or DBMS_Sl'M<DARD packages. We read more on except ions i n Chapte r 11 (Ha nd I i.ng Except io n sin P[l5QU.

The following code snippet shows a simple EXC~ Pl' ION section of PUSQL program.

Afteru n dersta ndi ng th e block suuct me of PUSQ L progra m, let's stu dy v;, rious types a f blocks.

of Blocks

Depend i ng On the header section, there are two rna i n catego r i es of blocks~J norwmous b I ocks and named blocks. A third kind of block known as nested block is aiso available 11101 can contain one or more anonymous/named blacks. Lei', 110W study all these blocks in detail,

Blocks

Anonymous blocks, as the name suggem, are those blocks that do not have a name. Therefore, we do nOI have ~"y block header for these blocks, bul Ihe)' hove one or more sections. which .a reo (I ec lara t ion, execuj ion. a n (I exception. S i nee th~y do no l ha vo Li r'l,a 1"l"ICr we ell i"I not CoO II th em. Due to this, anonymous blocks are also nOI stored :in the database. However, an anonymous block c. n ca II oth er na rned blocks.

Use, of anonymous blocks in PLlSQL are:

[J Declaring variables that can be used in Ihe execuuon >ecliol1.

a Declaring cursors thai can be used in the execution section, Cursor, are used 10 access elements stored in a collection. We will study in detail about cursors in Chapter 7(U ndersla nd i ng Cu "or; in PUSQl).

21

I:l Exect.lling cursor S~LECT statement.

Named Blocks

Named block, are In" blocks that have some name, II is obvious that if a block is a, named block, it would contain" block header because the name of the block is defined in a block header, Therefore, any named block would contain at INS! two Or more block sections flti, is because the executionsection is J ne.:e".'Y section for an)' PIJSQI. block and if we make header compulsory then there would be two compulsory sccrlons in the block. Overall, iJ named block can have all the jour sections=block header, declaranon, execution. .and exception.

Nested Blocks

N0stod bloc ks are y~t J n other i mportiJ nt kin d of I' LlSQ L b I ocks. When we nil vc blocks p laced inside other blocks, we tilil this phenomenon as nesting and such blocks ore known 01 nested blocks, T hese nested bloc ks m i ght fu rther d i fier from eac h 01 her depend i ng on sever" I different crlterions. One of such irnpOfiJr>1 criterions is the level of nesting. Each Nested block hal a certain depth. This depth is the number of level, to which that block has been nested, ror example, if we hJV~ ,1 block within 0 block, then it i, said 10 be nested to level one. Ii the block cont4'l1 nl,."(1 inside I he b leek fu nh er contai ns a nether b I DC k, the n ( he leve I of nestl ng j ncreases ro two, N~"'t i ng i, allowed 0" I yin two seci io "s--execu t i on and exc ept i on-Qi th e PUS QL block.

l et's now discuss the vanous data type. available in I'USQL to store real world entitles, such as numbers, ~PX~ and lm;lges,

Introducing Datatypes

Having knowledge "bout: datatypcs is esscnucl before b~ginning with application development in any progr"mming language because datarypes form the most basic bui Iding blocks for developing on)' pr()8'~rn- PUSQL supports all the predefined datatypes in SQt_ and also some addi I i ona I ones. There has 10 be a dar J type for every v il 'iahl e or p~ rame ter in PUSQL Depending on the need of the appllcauon, we car> choose the datatype that suits us the best, Various datatypes available in PL-"SQ[r arc:

a Number Type's,

a Ch:u;icrer :.nd Sldng rvpes

CI Nati ona 1 C ha ra c to r Types

!J Boolean Tvpes

a LOB Types

!J Do te and T i rue Types !J Subtypes

Number Types

Number types are scalar dJtol)'p,:s. The dataiypes th"t hold single value are known as scalar datatypes. As the name 5ugge:sts, number types are used to store nlJmefi~ values. These numeric value, may include inlegers, real numbers, USUJliy, we use number types for fields that need

numbers as. values! such as .1ge~ measurement -

":"22:---------------------- -------------

U rheberrec htl lch gC5C h utztes Iv! ateri"

Cirapl", 2: PIJSQL [","Ii"I,

The number types arc further divided into following types:

CJ BINARY _INTEGER Cl NUMBER

1:1 PL5_INTECER

CJ BINARY_DOUBLE 1:1 BINARY_FLOAT

BINARY_INTEGER

!HN~.R¥_INTE;GER stores the signed integer in a two', compliment form. The range of bi""ry types Is from "'2147483647 (0 *2147463647. Thi, Iype is generally used when we need 10 perform arithmetk operations. It no, following sub typos:

Cl NATURAL: May store integer, in range from 0 10 2147483647. I:J POSITIVE: May store inl.egers in range from 1 to 2147483647.

o NATURALN: Same as NA'l'URAL, bUI cannot assign null 10 integer variables. I:J POSITIVEN: Same as ?OS rT1V!l, but cannot assign null 10 integer variables.

a 5IGNTYPE: It is used in programming tri-state logic that ls an integer variable can only have value either -1, O. or L

NUMBER

The NUMBER type can hald floanng-potm value, or integer> in the range from 1.0,10"-130 10 9.99,·10"125. The general syntax of NUMB2l\ type i, as follows:

I n the preced i ng 'y ntax:

I:J preci~ion: represents the total number of digits that a number variable can store.

a scale: represents the total number of digits that a number variable can contain 10 the right of the decimal. The scale can range from - 84 to 127. We can only use integer literals for specifying precision and scale.

Now, see the subtypes of the NUMBER lype:

I:J 0!lC:, ll2CH-'!AL, and NUMEfUC; Used to declare fixed-polnt numbers with precision up to 38 decimal digit"

I:J IXJUB,I,E PRf.Cr srON and fLO A'!': Used 10 dec I,)", ilon!itlg-point numbers with precision up to 38 decimal digits.

I:J REAL: Used to declare floating-potnt numbers with precision up I<> W decimal digi!>.

1:1 INTEGER, HIT and SHA.L.L,lN'l': Used 1.0 declare integer> with a precjston up to 38 decimal

digits. .

PLS _INTEGER

PLS rN'l'BGER type con store signed integer> in range from -2 t 47483647 to +2147483647. PLS IN'l'£GER datatype is more efficient than NUt1B£P dararype since ~!,s_rN'l',;G1;R values

23

U rheberrcc htl lch gesc h utztes Iv! aleri"

lake less storage than NUMBER values and also lise hardware ar'ilhrnelic for operations 'involving them, Oracle recommend, the use of Pl.S_l:<TEGER over B1NARY_n:lT1:GER for developing new" pp I i catio ns.

BINAR,Y _DOUBLE

BINARY_DOUBLE datatype was released for the first time with Oracle 109 release 1. II is called "INl\RY_OOU3Li: because it i, On IEEE·75·j double precision floating datatype.

Liter,1ls of B,INi\llY _OOUSU: type end with d, "Kh ;,'5 1.005&J4d, It is .. high precision datatype, which is gener,'lly used to measure system performance, It is used (0 measure performance because worki ng with system parameters requires performing several cornpl icated calculations 'correct to several decirnal places,

B,INARV_FlOAT

BINIIRl'_FLDAT datatype i, newly introduced with the Oracle tOg release 1. It is also used 10 perform high precision scientific calculations but unlike BINARY_'XlIJBLS, it is ,ingle precision float data type. However, it finds a sirnilar application IC) BrN~RY_ OOUBLE daiatvpe in m"Jscrring performance g~in,. tucrals of SI'<ARY'_Fl.QAT Iype end with f, such a. 3,871.

Character and String Types

The chara cter Or stri ng type, in PUSQL arc used to Ito re everyth j ng from, i ngl c ch aractcr va I UC5 (0 'IJ.rge Itrjng.~ up to 32K in size, We Can use these types 10 store letters, numbers, or binary data, We can also store any character supported by the database character set using this type, Character types are also scalar types, Various differ""t datatypes that are inriu<iL'{i in this Il'pe ore

as follows: '

CI CHAR
0 toNG
0 LONG RAW
a NCHAR
(J NVARCHAR2
0 RAW
(;3 ROWID
(;3 UROWID
o V,\RCHAR
Q Vi\RCHAR2
CHAR C1L~R is a fixed length daratype. By delJult, clM.a is stored in bytes, Ii is ,m,,,1I1' used 10 store the basic character type values, tnternal representation of characters depends UpOFl database character SN (ASCII, EBCDIC, .. :i. The genera' syntax of CHi'.R data type is J' follow."

C~~~[(.iz. [CHAR I sVTElJl .";. ".'. ci"r,

The size I ueral can have value from I to 32767, The size can be in terms of characters or bytes, "Therefore, upper limit of CJf.~.R variable is 32767 bytes but we cannot insert CHAR values gre;)ler than 2000 byle~ in CHAR database column. Default value of size ~5 I.

24

U rheberrec htl lch gC5C h utztes Iv! ateri"

2: Essen' ial.$

LONG Iype is "sed 10 store variable-length character strings. It tan 110Id values up to 32760 bytes. Note thai the long type in PLlSQL is different from the LONG database column used in Oracle database. Maximum width of LONG column in Oracle database is 2147483648 bytes .•

we can insen. LONG value into LDNG column but we cannot do vice versa.

RAW is similar to the LONG type but i!., can also store binary data in addition to storing

strings. ..~ ..

You are alre.dy aware of ASCII and EBCDIC character sets. which are used to represent roman These alphabets are internally stored only in one byte but some characters of Asian such as japanese need more byte; for their internal storage representation. Therefore,

provides globali~ation support to run Oracle applications in mony I~nguage environments. Two character sets that are used for intemoti()nalizing (or globalizing) an

application are database character set, and national character sel. .. .

National character set ls used lor national language data. National character set represents data

two encoding5-UlF8 and AL 16UTF16. In UTfB encoding. each character may be stored 1, 2,. or ) bytes depending upon runtime length requirement. In A116UTF16 encoding, each is stored in 2 bytes whether a string consists of ASCII characters or not. This ls more encoding at runtime,

hold, fixed-length national character data. Internal storage representation of string depends upon specilied national character set with specified encoding. The genet,,1 syntax of IlCHAR data type is as follows:

Sile in this syntax h; an integer I ireral. The upper limit of slze literal ls 32767(2 for AL 16UTF15 encoding and 3276713 for UTF8 encoding. The maximum size 01 NCHIIR database is 2000 bytes; therefore, you cannot insert. 1'CHAR value, exceeding 20110 bytes into a database column.

can assign a CHAR value into ~ NCHAR variable but opposite assignment results into loss of bytes.

holds vanable-length character data. It is identical 10 the VhIKHl\1l2 type, but takes character set specitied by Ihe National Character Set. The gene'al syntax of NVk<'CHAR2 as follows:

25

U rheberrcc htl lch gesc h (jutes M ateri a

In thi, synlax, the size ls a literal. The upper limit of ,ize lil~ral is 32767/2 for AL16UTF16 encoding and 327(>7/3 for UTF8 encoding, As maximum size of NCIIAR d.ll.abase column is 4000 hyles, therefore you cannot Jnsert NCHIIR values exceeding 4000 bytes into a NCHAR daw base col u mn.

You can assign VARC!!AR2 value into" t<fVAI<CHAR2 variable but opposite assignment results inlo loss of some bytes.

RAW

The RAW type stores fixed-length binary data, such a, a set of graphic characters and can hold up 10 J2K (32,767 hvtes), The general syntax of RAW types is as follows:

!,,'T'·.~RAI((.str.,)l'I:i1>:"''I1IIIIIII.'' ••• IPJi;I\i''.IiIiIlia.''IiIIlII.IIWIi .. IIIt!=~!.'''',.. The size is an inleg~"f literal and can have values from 1 to 32767. Since the RAW column of Oracle database can hold only 2 Kilo bytes, therefore, we cannot insert RAW value into RAW column. w~ can store RAW value into LONG RAI'l database column. We also cannot retrieve value of the LOtiG RIIW column into !.ONG RAW variable.

RDWID

"very record in a database table internally contains a unique binary value called a P,OWID. The rowid is storage address of the row. The rowids Can be of two iypes-phylical and logical. Physkal rowlds provide quick access to specific rows. By default, there is one physlcalrowkl for each row in the database table, Physical row id can be oi two formats-s--l O-byte extended rowld format and 6.byt(, llmlted rowid format. YOLJ CJn also r~lricv<) the rowid of" particular row. SQl • Plus automatically changes binary rowid into character rowid, Execute the ioHowing query 10 see rowid:

,.",1."" ·r<iWjd.'._:;f.r;:'l!OA!Q""$>,,,,hefe;'_Jd..tQ2v,,,",'.'oU"·.·"I:oI.>~;·,i~m Thi!\ query gerlerates the following row:

~cwf:id . ...~~. AAA'l.+bAA~vAA8' "a.aurav

The general formal ofreceived rowid is OOOOOOFHBBBBBBRRR. This rowid formal has following iour components;

!J 000000, These six 0', represent database segment, In our case, it. ts ,'.Al,L+b. Thi, number is ,,150 called data object number.

a fff' These three F's represent file number that recognizes data file, which consists the row.

In Our case, it is AP.r.

!J 888 B8 B: These six B'. represen t block rt tim be r that rccogn i zes ria ta block, W h i ch cons i,ts

the row. In our case. it is .~Pll\MW.

o RRR: These three R'. represent the row in data block.

Logica I rowi ds provi de qui cker accesses to part i cu I ar rows. Ora de uses these rowids to make secondarvmdexes on i"de,,;,,] tables. If we change location of the row, its logical rowid remain. Same.

26

U rhcberrec htl lch gesc h utztes M ateri"

a'.pler 2, I'USQI. Esse" I ials

ROWID type can only store physical rowids not lcgical ones, You need to be caretu I when retrieving and storing database rowid into ROWID variable or vice versa. Use RO~'1 DT"OCHAR function to convert binary value in,o 18 byte character ~Iring when fetdling database rowidInto ROW1 D variable; otherwise, use CHARTOROW, D function.

UROWID

OROW!P provides ,uppor! for storing both physical and Ingical rowid s. There is no need to use conversion functions when relrieving or storing IJRQI-ll D variabte into IJROWI I) database column. The UROW); P column can store maximum 4000 bytes.

VARCHAR2

VIIRCHIIR2 data IYIJe ·is used 10 siore vari<lble·lenglh character data. The general syntax of

V.i'.RCH.1I1l2· d,,(;) t)ipe is .1S follows- - -

The size in this syntax must be integer literal. It can take value from 1 to 32767. VARCHAR2 variables having length shorter than 2000 byte, am known a, small IIARCHAR2 variables, For these variables, PUSQL statically allocates memory e(]"al to declared size of variable. For larger variable" PUSQl allocates memory dyrmmically whose size i, just enough to 'tore runtime value. Note that you cannot insert VIIRCHAR2 values great.cr than 4000 bytes into VARC~1\1l2 database co I u mn,

We can insert VAf>cCHIIR2 values into LONG database column out we cannot retrieve value of LONG database column into VIIRCHIIR2 variable.

The subtypes of VARCHAR2 are STRENG and VARCHlll". These types have the some range a, that of Vt\RCHAR2 type,

VARCHAR

VARCHAR ls an ANSI.slandard SQL type, 'ynon.ymou, with VARCHAR2. OrJele recommend, using VAilCHAR2 to protect ~gainst, fut.ure modifications to VARCIlAR impilct_ing code.

80018an Types

I'USQL supports BOOLEAN data type to represent logica:! value,-TRU8, r.~1S£, and NULL. You Can ""ign NULL value to a 8001E1IN variable when you do not know either vdlue of the variable or assigning value 10 a variable does not make an)' sense for a particular record in table or variable. For example. in record of employee who holds designation of a software engineer, com", _pet variable or fie I d, wh i ch represents percen rage of com mi ss ion does not I." ke J ny value but for a sales person, commission matters and CQ:YL"";'l-"ocr.. variable has. some definite value. Therefore, co",", yet variable may be JS'igned to NULL value for wflw"re engineer. N01e that you cannot use BOOLEAN variables in SQL queries since SQL docs not support BOOLEAN data type. This note also implies that you neither insert. MOLEAN values into a database column nor retrieve column values into BOOLEAN variable.

You cannot use quotes when assigning TRUE, FALSE, or NUL.I. values. to a BOOLEAN variable else you wlll encounter an error. listing 2.2 tries 10 assign TRUE as a character string to 0 Boolean variJble.

27

U rheberrcc htl lch gesc h (jutes Iv! ateri"

tisling 2.2: As,igning character variable 10 boolean variable

On execution on iSQL "Plus, Lisling 2.2 generales following output:

The output show, error expression ls of wrong type in line 4.

LOB Types

LO B sta n cis lor la rge ob j ec I, PUSQl supporlS va ri ous La B da I a types, such as B, I LE" B W B, CLOB, and NCWB. The", datatypcs can store text, graphic" audio, and video dip'. Size of BLOB. CLOB. and NCWB datatypes ranges from 8 10 128 terabytes bul size of BrILE is system dependent and cannot exceed than 4 gigab),tes.

WE! type, orc manipulated through lob pointers which can point to large objects stored in external Ii le, inside or outside the row. WB database columns also store' loblocators. When you [etch a WS column value, you get only lob pointer. This lob pointer is used to manipulate correspondmg large object, You can use e<isling package DBMS _ LOB 10 perform read and write operationson LOBs.

You ca n also conve rI CL 0 B, 10 CHAR, VARC H.AR2 I vpes or BLOB, 10 RAW an d vice versa.

BFllE OatatypB

BfI LE datatype is used to store large bino,y objects in Op~J;)ling system files outside the database. The polnter stored in BFI LE variable point' 10 large binary f Ie on server and contains lull path 01 binary file. These BfILE variables ore read only, Note that you can limlt rhe number of opened BflLEs by setting Oracle inili.lizalion parameter SESSION_MAX_OPEN_rILES. This pararne ter is n I '0 'y'len" dep enden I.

BLOB Oatatyp B

BLO B de ra type is u sed 10 510 re I a rge b i na ry ob j ects in the cia ta b ase, in 5i de or ou tside the rOW. You can usc only BLOB, not BFI LEs in transactions . You can "1'0 either revert bock or commit changes made 10 BLOBs using DHMS _ LOB package.

CLO B Oalatype

CLOS data type is used 10 store large group of character data in the database, imide or outside the 'ow. CLOBs parucipate in rransacuons and you CJ>O either revert back Or commit changes marie 10 CLOBs using DBMS_WB package.

28

NeLDB Datatype

NCLOB data type is used to store both fixed and variable length NCHAR character blocks. NelOBs participate in transactions and you can either revert back or commit changes made to NeLOB" using DBMS_LOB package.

Dau" Time, and Interval Types

Both date and time are stored in one variable called daietlrne variable, and tlrne periods are stored in another data type called interval datatvpe.

DATE Datatype

DATE data type Is "sed to store fixed length date and lime in which time is specified in seconds, Oracle initialization parameter NLS_DATE_FDRMAI determines default dale format. Usually, default date format is 'DD-MaN-YY' where [)D is two digit number lor day, M:JN is abbreviation for month, YY includes last two digits of year:

You can extract time from OAT£ variable in the following two steps:

o Use SYSDA'I'E built-in function 10 get curren I date and time and store il in variable S.l.y

.da loa _ var l.able.

!J Extract the current time u~ing date_va r iable-TRIJf:Cida te _.'-in i.able).

You can perform other operations, such as comparing two dales, arithmetic operations on DATE; variables. For example, SYSO,\T£+l returns the same time for tomorrow.

TIMESTAMP Datatype ,

The TlMES'I'AHP data type extends D'ATE datatvpe and store day, month, year, hour, minLte, and second. The seconds field can store seconds in fractions, The gener"1 syntax of'!' 1 M£S1"AMP data t:y pe is a, {oil ()W$;

~..w[(Pfe-:Ci $.:tbn111m~·~~r.:·:.:.:;t.".· '~,;- ".;-!"\ .>: "... ':-.- _··~·::tt~;~;i~l· .: .: ,;_. -. ;~'~.:~;~~~::.:t;~~ '::~/-i~'

Where precision is integer literal between 0 to 9 and specifies number of digits in fraction"1 part of seconds field_ Oracle initialization parameter ~LS TlMES'I'AMP ,FDRMA7 determines the

default timestamp format. _ _

TIMESTAMP WITH TIME ZONE Datatypa

The TH1ES1'AMP IH~'H'nM,:, ZONE datatvpe extends T r~!ESTAMP datatvpe and also includes difference between local and Greenwich Me~n Time time zones, The general syntax of this datatype is as follows:

Where precision determines number of digils in fractional pan of second, field. Oracle lnltlallzatlon parameter NLS_TI!~ESTA""iP _TZ_FoRMAT determine, the default ttrnesramp with time zone formal. Following are some examples 01 TII-lESTAMP IlI'THTIME ZONE values:

29

U rheberrec htl lch gesc h (jutes Iv! ateri"

In this example, time-lone displacement in the firSI TH1ESTI\MP is +02 ;OQ. Second and third valees ore same but 'later specifies lime zone by syrobol ic name, such as USJ?acific_ You can see symbol ic names of other zones by executing following query On iSQL ·PI"s.

SELeCT • fROM V$TIM oZONE___,......,ES ;

TIMESTAMP WITH LOCAL TIME ZONE Datatypa

The TIM.ESTAMP \'lITH WCAL TIME ZUNE data type extends TIH~STA1'!P dow type and includes lime zone displacement. Differ·ence between T IMSTAHP WITH LOCAL TIME ZONE and TIMSTAMP WITH TIME ZON£ is IhJI value of the TIMSTAMP WITH TIME ZONE is not stored in a database column while value of TIMSTAMP WI TH lOCAL TIME ZONE: is stored in the d~!i1h~$e lime zone and is ~lIlom~lical,ly nornlaliled_

We a rcex p I" in i 'n,g you normal i zati 0 n vvi I h I he help of J n ex" rnple . For ex" mpl e, he" d department of on organization would I ike 10 know about the number 0; orders placed ye,slerciay ;"iIS differenl departments. All departments are remolely located and they have different lime z ones. The ref ore, yeste rda y means eli FFere n I cia Ie and times in loc or ions 0 r ot her depa rime n15. If h cad of I he dcpartrn ent dec I ares 0 RDE:R . DATE col urn n 01 T I ME S T A.'1P torr T fI LOCAL T I ME ZO N E: data type, I hen d ifferenl do I~'S an d lim es of placed orders are au tornat i call y co n verted (normal i zed) i nto I i me zone of th e hea d of departme nt.

INTERIIAL YEAR TO MONTH Datatypa

The IN TE RVAL Y E All TO t''Ll NT H do I~ type is used 10 storein te rva Is i n ye~ rs an d mo nths. Th e general <yl1l.1X of this data Iype is as follows:

INTERVAL YEAR ( (prect sion)]: TO MONiTH

Where precision is an integer literal in range 0 10 4 and denotes the number of digils in years filed. See l.lstlng 2.3 which shows the lise of I NTERVIIL YEM, TO MONTH datatvpe.

ti<ling z.s. Use of INTERVAL YEAR TO MONTH daiatype

firSI ~ssignmenl statement assigns a" irnerva] of 10 years and 1 month 10 a t.Lrnep .. dod variable. In second assignment statement, Oracle automatically converts character literal '10-1' 10 i ntcrva I typ e. Th i rd and 10 urth ilSsig nm ent statements cha nge t i rnepe ri od va ri a b r e 10 contain interval of years and interval of months respectively.

INTERIIAL DAY TO SECONO Dat~type

The INTERVAL DAY TO SECOND dataivpe is used 1.0 store interv~l! in d~ys, hours, minutes, and seconds, The general syntax of this data Iype is as iollows:

30

WheJe precis ion 1 and precis ion2 lell the number of dig,it, in d~y and second fields respectively. Both precision! and precis ion.2 are integer literals and C,.J,I1 take values in the range 0 to 9, Listing 2.4 shows the use 01 INT~RVI\L DAY TO SEOOND datatypa,

li sti ng 2.4; Use of I NT ERVAL DAY TO S ECQ N D cia tatvpc

This example check> how much extra lime an organilalion Silent on 11 project.

You are al"'ddy well aware 01 values that day, month. and yea, can toke. Table 2,1 hsts all values that various fields under dale, time,and interval types can take.

31

Pl/SOJ. Subtypes

PUSQL subtype defines a range of values and a set of operations 011 variables of predenned PLlSQl datatype, These restriction, are defined on already existing PUSQL type, Therefore, subtype is not ":ny new data type and it is the one that is derived from exi5ting PUSQL deia types, PUSQl has also defined some subtypes in STANDARD package, For example, CHARACTER and INTEGER data types in PUSQl are defined a, follow,:

:51;;1 STIPE CHARACTER I S CHAR; SuBTYpE INT£G:E~ IS NUM8ER(38, 0):

from these definition" CHARACTER subtype is the same as C~AR datatype but ~n INTEGER su btype cons i sis of on I)' J 8 eli gi Is.

User defined data type, are .150 declared using following :PUSQL syntax:

S.1,HIiTYPE sub typenarae rs baset ypej (co.nSt)] [iNert NULL]:

Where sub t ypaname ls narn e of a new sub lyp", ba s e t ypa is name of already exi,ling :PUSQl typ", and const specifies size of new sub Iype, following example declares subtype named bela te Ihat con rake null value,

,usn." boa te J 5 OA TE NOT NU u,

Let's now discuss syntactic elements of PUSQL., such as delimiters, identifiers, and lite,~Is.

Introducing Lexical Units

You CDn choose characters out of alphabets (A. .. Z, J .. .z), numbers 10, '" 9), symbols 1+ - • 1< > =! - " ; : .( I ' @ % , ";: S & _ I { ) ? I II, labs, and spaces to write il PUSQL program. The group of characters in a PUSQL line 01 code is called lexical units. lexical un itin PUSQl may contain a single character or more Ih,,,, one chor,lCle·r. -A l'ine of PUSQL block can ccntain following lexical units:

0 Delimiters
0 ldenriflers
D ttterals
D Comments Delimiters

A delimiter is a symbol or " set of symbols that has predefined meaning in I'USQl, For example, + del imiter represents arithmetic operat ion and . ~ delimiter represents a«ignmer11 operator. See Table 2.2 for del irnilers containing only one symbol.

DelimitDI

Name

+

Additiol'l eperater

'~,

32

U rhcberrec htl lch gesc h (jules M ateri"t

U rhebe rrec hthc h gas 0 h utztes 8 i {l

Identifiers

An identifier is .J. name given to constants, variables .. exceptions, cursors, cursor variables, sub programs, and packages, This nome should start with a leiter thai may be followed by more lett ers, n u rnbe rs, dollar 'igm, underscores, and n u mbe r sign" The na me of i den! i fie r ca nnot contain hyphen, slashes, and space,. The identifier caricomatn less than or equal \0 30 characters, You can also use more than one dollar Sigh, underscores, and number signs.

Some example, of identiflers are A. temp2, oame." time_limit, ,iutName, and R. TI)' to make identifiers descriptive and meaningful, For example, use variable name as percent instead of pet Some non-examples of identifiers arc time-limit, either/or, emp name, and i.su,

Reserved Words

There ex iS15 a .I 0 ng I i st of ide n tlflers in PLlSQ L w ilh each i denti fief h avi ng .i ts spec i fie .ly ntactic meaning to PLlSQl. These identifiers are called reserved words. If you try to redefine them, then they cause compilation error, For example, BEGIN and END are reserved word, tndlcatlng the begi nn i ng an d end 0 f b'l ock respective I y. Here is" rt exa m pre wh ich me, BEG I N word fo r the name of variable of D1\1$ Iype_

U,llaberrachlllch g"'Chl~2t"" 81j

Wh en you exec ute th is code s ni ppet on i SQL 'PI us consc I e, an erro r -OCClJ rs.

34

U rhebarrec h tllc h g sc h utztes Maieri"

Predefined Identifiers

Identifier, declared in the STI.NDhRD package are called predefined identifiers but these identifiers can be redeclared, Rededaration of identifier overrides the declaration of the same identifier in STAN DARD package,

Quoted Identifiers

Pl./SQL supports ldentluers enclosed in double quotes, These identifier, used to contain a sequence of character> (excluding dDuble quotes) to be printed. Number of characters in double quotes cannot exceed 30. For example! "1\+'611, n .. :i ** w:ri t e a p.rogl.'.;.m t:o find square root of number

literals

Literal represents numeric, character, or Boolean value. It is not the name of Jny variable. Example of numeric literal Js 135 and Boolean I iterJI is TRUE. titerals are divided into following categories:

o Numeric literal

o Character l.iteral

o String Literal

o Boo I ea n Li teral IJ Datcti me Litera I

Numeric Literal

The numeric literals arc used in arithmetic expressions. These luerals are of two types ...... ir>l.eger and real. .An integer literal is" number (siSf' not compulsory) without decimal point. Examples oj integer literals are 025, }4,·67, and +3456. A real IiterJI is J whole or <1 fracnonal number with decimal point. The sign is not compulsory here also. Examples of real literals are 7 A.165 7, 0.0.·23.67, .6, and 24.0.

Scientific notations "1'0 contain some numeric literals, such as 3 E5 or 3e5, 3.1414eO, and 5e-3. In these literals, E or e is 10 and the number auer E Or C is power of ten. To write a number using sclentjflc notation, ,ufiix the number wilh an (E or c:) followed by an opuonally signed integer.

Note that you cannot assign literal value 10 J variable grea1er than tne upper limit of the variable's daiatvpe,

Cheracter Literal

A character literal i50 a singln character enclosed in single quotes. This sillgle character can be any character of rUSQL character set, Examples of characier llterals are ',a', '1\', and 'C. Nole that 'a' literal is different irom '.~'.

Stri ng Literal

A string Iller,,1 is, a sequence of zero Or more characters enclosed in single quotes. Exampl'cl oj' string literals are '.ABC pvt, Ltd', '$154.99'. If you need to use character literals, such as I 'rn ill, then add one more apostrophe before' cpostrophe within J string JS shown here-- 'I "",. ill'.

35

U rheberrec htl lch gesc h (jutes Iv! ateri"

Boolean Literal

Boolean literal tokes 'logical values, such as TRUE, fALSE, and NULL. The NULL lileral stands (0 r m i ssi ng, unknown, or ; napp I i Co b le va I ue,

Datetime Literal

Datenrne literals can have di(rcrent types of date lime values depending upon the dam Iype. Listing 1.5 declare, various types of dateurne literals,

Lis1ing 2.5: Declaring dilferenl dateume literals

In this example, a 'is ollTE literal, t s l ls TIMESTAH~ literal, "52 is TIHESTAMP WITH TIM,E ZONE' literal, i yrrnl is I NTERVAJ.. I ileral lpecified in vears and months, and i ats2 is INTERVAL I ileral specified in days and seconds.

Comments

The P LlSQ L co mp i I er does no I mmp i I e com men Is i n it PLlSQ L program bu I th is does n 01 mea n tha t devcl 0 pers shou Id nOI add (om men I~. Com m ents "rIO user f r; end I y an d help in bell er undorsrandtng of PLlSQL program, PilSQL supports IWO types of cornmc.us-s-slngle line comments and rnuttl Hnc comments.

S ingl B Lin!} CD mm e nts

Single line comments stan with double hyphen (--J and ends at the end of line. Usuall)", they appear at I.he end 01 PUSQl statements. Here is an example of single line comment

Two single line comments in this code snippet explain the meaning of interval literals iytml and Ldt s 2, First comment tells lhe use' Ihal i yt.m l I;teral stores interval or ten years and one month. Second cornrneru tell, the user thai .i dt 52 I ilGJI stores interval of time duration of Mound three day" five hours. three minutes, two and 1/100 seconds.

You ma), use single line comments 10 comment QUI (or disable) In)' statement during testing or deblJg,grnB of progr4-1m.

Multi-lille Comments

Multi-line comment starts with t- symbol and ends wilh "], In bel ween these symbols, there may be one Or more than one line, which explain, funClion~lit)' 01 the specific portion of PUSQL program to user. Listing 2.6 is an example of multi-line comment.

36

C i'rlpler 2: PUS QL £,"" tial.

Listing '2,.6: A n ex ample 01 mull i·1i ne co rnme ru

The multi line comment tells user about aethor and functionalily of the procedure. With the help of m u I ti lin e com ments, you Co n disa b le sectio n 5 01 code d uri ng d ebu ggi n g of rl.lSQ L program. Lei's now discuss how 10 declare variables and constants with restrictions and assigning DEFAULT values to them.

Working with Declarations

You can declare variables and constants which are used to store values in any PUSQl block" sub program, or package. Each declaration 01 variable ,pecifies it, data lype and name of storage space allocated by PI.ISQL compiler. This name i, further used to acces 0' manipulate il. Following example declares some variable, and constants:

This example dec I" res mat.chdat e variable of DA,TE: Iype, nco rma ccne s constant of INTEGER type, and manofma[ch constant of REAL type, Both constants are also initialized S i nee the va I we of consta n 1 does not c h a nge du ring exec ul ion 0 r the program.

USing OEfAUl T ViliuB

Keyword DEFAULT is used in place of assignment operator 10 iniuallze variables ihat have some 'pedro, value. For example,

vartables have some already predefined values.

You may use DEE"AULT keyword to initialize cursor and subprogram parameters and fields in ;) use r -defl ned record.

Constrilint

can impose constraints on a variable, such as variable can accept null va lue. ti you assign null value 10 variable declared as NOT NULL, PLlSQL engine generales predefined VALUE ERROR exception. You can declare a variable a, NOT NULL as follows:

37

ThiS code snippet defines Account_NQ variable as NOT NULL.

Using Aliases

Alia,es are used when the Cursor is defined with theexpressions. Aliases con also be used in the case whe n you are se I ect i n g so m e val ues from the database lob I e an d w~ nt 10 di splay the set of retrieved values through a single variable. That variable is known as alias. Listing 2.' lllustrates the use of "lias in St;LECT statement

listing 2.1: Use of alia,

Jrhel err '11111 r 9 scl1u12les Bi d

ThiS exampte Jssigns alios ful.l name 10 first. name I I' 'I I las t name expression. In loop, we are accessing fu11_ name from record having lull names of r.,~t7o"r employees .. Let"s now move on 10 understand and use differenllype' or operators available in PUSQL

Introducing Operators

PUS Q L su pports a set 0 f operators wh icn are helpl u I in bu i ldi ng a var i ely 0 f express ions. Express: 0 ns co ns is lor operators, wh i ch act u po n opera nds and generate a result. All exp ress ions return only one value. We are now dlscusslng "II Iype of operators available in PUSQL.

Assignment Operator

A5SigJ1m~nl operator (:=) in PlISQL is USH{iIO ""igl1 a simple value or expression [0 a variable on its left side. Foflowing example assigns value of expression 10 Quantily variable.

Urilebe"BGr.~lc~ qaschCrtzles Bild

You can as:iigrl a: value to a suitable v3riable in 3ihy section, such as declaration. execunon, or exception. If you do not assign u,,), value to a variable in dedaration section, then il is assumed 10 SIQre NULL value,

You can also a,sign a iunctlon call 1,0 variable 50 that Variable wi'll store the value when returned by f u netic n, As> ign men I operator is used 10 hoi d Oy na m i c SQ L ,I" tern ents i nl 0 a strl ng variab I e.

38

U rhebarrec h tllc h g sc h utztes Maieri"

The EXECUTE IMMEDIIITE command takes this string variable and executes the query, Here is an example;

UrllCberrecrtl_h g ,scrutzlus Bild

Arithmetic Operators

PUSQl supports mathematical operators, such as addition 1+), subtraction H, multiplication (-), division (I) to build and evaluate arithmetic expressions. Usuall)f" multiplication and division have. higher priority as compared to addition and subtraction. Parentheses can change the order of evaluation of an expresslon. For example. when PUSQL engine evaluates (10+6)/2 expression, fi"t adclirion is per'formed, then division is performed and Ihe result is 8 nOI 13. An arithmetiC expression can contain nested par e ntheses ill which deeply, nested sub expression is evaluated first, For example, 10 .. 1612+(5·3)) generales 15.

Logical Operators

PUSQL also support, logical operators" such as liND, OR, and NOT 10 form logical expressions. The AND and OR operators are binary operators a, they require Iwo operand, but NOT is a unary operator. Table 2.4 IiIIS truth table for each logical operator.

If we see the truth table of each operator, we find that liND returns TRUll value only if both of i(s operands are true, OR returns TRU~ if any of its operands is true, and NOT operator returns the logi ca I n egat i on of i Is opera I1d.

Parentheses may change the order of evalLlotion of logical expression.

39

--_._--------------------_

Comparison Operators

COll'p,"ljriSOI1 operators are used 1.0 compare imple values or expressions. These operators- are used in conditional corurol >I,)lernenl$ ~n(ll·lHERE clause of SQt DM!. statements. Table 2.5 li'I' JII the comparison operators.

Operator

Pu.rpose

Checks wheIb", its op.r".d. are .quol.

>=

Check. whether left sid. operand is g .... I.r _ (II. right lid. opo ... d.

Checks whether 1811 side operand is less than OJ .qual 10 tbe right aid. operand.

Chocks whether left aid. oporand i. greater Ihan or equal 10 tho right lid. ope<8nd.

>

<=

IS NUll Operator

The IS NULL operator is used 10 check whether its operand is null or nor. This operator returns TRUE if the operand is null, otherwise FALSE.

11= liar IS NULL THEN

Concatenation Operator

Concatenal ion operator, denoted b)' double vertical bMS (I I) concatenates two stri ngs of type, such ,1S CHitR. VARCHAR2, and CL08. For example.

set server-output en:

BEGIN

oa"S_OUTPUT. PUl_L1NE(' I' II'you'); E~O:

I

This example outputs string '!You'. D"ta t)'PC of "utpeot >Iring depend, upon (1"latypes of the operands. If CHAR is the data type of both operands. then the output string obta tned "fief concatenation wi II hove CH".R data type. If one of the operands has data type CLOB, then result will be of CLOS dam type. Ii one of operands is VAl<CHAR2, then result will be of V.~RCE".R2 data iyp .

LIKE Operator

t~IKE operator j,s used 10 compare singh;' ChM.r1CWf! :SIring, or CLOB value to a specHied pattern. Case of characters matters during cornpari on 01 s!ring with !J pattern. If 'Siring matches with the specified pattern, then LIKE operator returns Boolean TRUE:; (Otherwise. il returns fi'.LSE.

40

U rhcberrec htl ich gesc h utztes M aleri"

Q,opt" 2, PUSQL E,,,,,,lio/,

Patterns used with L1 K£ operator can include two ,imporWnt characters called wildcardsunderscore (j, percent 'ign (%). The underscore U character check, whether there is only One character present in the actual string between characters surrounding underscore U in pattern. The perce n lsi gn ('Yo) character Ii n ds wh el her zero Or more ch a, ecters are preseot : n actu a I Sl ri ~Il. Here is an example:

!imlR.'I,I,IJ·ier.:.~e.l'\Me .. l ; k.e 'T%N._R, r i Th ls qu ery resu Its in 1.0 foil owi ng record'

MPNO W>.HE"'"I'j~B~' ., ,!'!GR.-,:. H.IREDAn:

~~LSEMAN .l!7698 0.8~SEPc'8l '1500

If actual string contains % or_characters, then yo," need to define an escape character which is put before the % or _ in pattern For example:

IF di 'CO"ltt UKE 'SO\% off' ES","PE,;!,\' ,TllEN .•

There rna)' be some real lime entitles in world that may have % or _ , such as marks, user ids. or email ids,

Range Operator: BETWEEN

The BETWEEN operator checks whether value of the variable lies in a specifled range. It returns TRUE in fo'ilowing cases:

I:J When value 01 variable equals to lower bound 01 range

I:J When value of variable is greater than lower bound and less than upper bound c Whe n va I ue 01 variable equa I s u ppe r bou nd

Otherwise, it 'return, ~ALSE value.

Let', use BETNE:EN operator, See the following que')':'

se lecn

ro~, emp, WH:ER~SAL ,.BIT<ni:EN 3000 ~D 5000:

This query result fetches following records from table erup,

list Operator: IN

The J N operator di frer's Ira m BE; T;IE E N operator as it spec iii es a set 01 me rn bers or va I ""5 bu t BE;T\,EEN operator onlv specifies lower and upper bound" This set 01 values=can contain null v ill uos, Th is operator is u sed wile n th e user knows a I 1 set of val ues and wan Is 10 re trieve rows of table corresponding to these values, For example.

41

This query fetches and displaY' rows oi amp table having eriame JONES. C L.',RK. and fORO.

Y <J II he V~ u nderstood "II (ypes of o perators bu I I here are some I' LIS Q L ~ xpressio ns "') n ta i ni ng operators from different categories. To understand evaluation oi these expressions, you must be aware of operator precedence of all operators. Table 2.6 lists the Operators precedence.

ANti OR

Logical AND LogIcal DR

Now we describe various auributes USt!I;J tu gel inlorrnatjon about data type and structure of da t:abil sc en ~ iti es.

Introducing Attributes

PlfSQL variables and cursors have s~.and.'fd ",llributC's, that are used 10 access [he properties. such t.1S, datil type, structure of database tables. PUSQL supports. two HUribwps-t)thTY PE and %ROi(lj'fY PE_ Each has a prefix 0/0.

Using the %TYPEAttrihute

The o/vTYJ?E attribute is used to define variables with data type same as Ihat 0' database column. Suppose that there is <;1 column named name in table ernp. To declare a variable n~IT_'31 with data type of name column. use %'J',,{ p~ attribute as follows:

If databose adminisnotor chaTlgG(! the d·ata type oi name colt .... nn, data Iype 'Oi flame 1 vartabte wi II also change .11 run time.

42

U rheberrec htl lch ge5c h utztes Iv! ateri a

2; E~[m tiais

Attrihute

attrtbuie is used whh records. A record is composed of a set of related fields each fidd bas a data value, The %RO~1'j'YPE attribute declares <1 record type. which Is as the row of a speclfied table. The declared "''';0''] CJh also store the record felched hom

code sn ippel dec la res an f; mp t: e c record with he I ds I h4~t have sa me tid rnes 41Jid data

".5 col urn ns in E M ~ table: -

further access value, of field, of record in some varlable as following:

we put all the operators for building PUSQL expressions.

PLlSQL Expressions

of operators, which act upon operands and generate a result, An operand can constant. literal, ()J (,mel ion call, which results into a value, PUSQL supports two of operators=-unary and binary. Unary opera lor, operate on only one operand and binary operate on two ope ra nds, A II m'pre.5s ions retur non I y 0 ne va I ue. The data lype of va 10 e opon dWlIY-Pe5 of other operand, and lypO of opera lor.

can usc expression, in both SOL and procedural statements. In most cases, Boolean are used. Boolean expressions ;;HC made up Or simple or complex expressions, which comparisons using relational operators" l.oglcal operators, such as AND, ORr and NO'i' connect these Boolean expressions 10 build more complex expressions, These expressions result into TRUE!, fALSE! or NULL value.

SQL statements, Boolean expressions are firsl used 10 find J particular row of a table and tile is executed On Ihal row. In procedural statements Boolean expressions ore used to conditions, of conditional control statements, such as i ~'-THEN, T:?~'THEN-F:LSE_

supports three types of Boolean expressions-c-arithmetic, character, and date.

AriUimetic Expressions

arithmetic expressions involve the quantitative comparisons of numbers, For example. num; Jnd num2 are two integer variables assigned minteger values 45 and 23

43

U rheberrec htl lch ge5c h utztes Iv! aleri"

This expression results into TRUE value.

Boolean Character Expressions

Boolean character expressions invo~e comoarisons of character values, These performed On binary rep[e,enta~~.~ v~tL:!!I~.! .. 9 .. !::~.IL;:::!~.~B.I~t example.

The expression in thls example results lnto TRlJE value, You can make based. Th is is done by setti ng NL S _ OOMP pamm eter to ANSI. These compa ri son.

using collating sequences. A collating sequence represeots characters in a character set numeric code, so that character strings can be compared,

You can make other types of comparisons, such as case-insensitive, acccnt-insensrtlvc by cha ngi ng the va I u e of N LS _ SORT parameter. If you wa nt 10 perform case- i n sensl tive cornparlson, append _cr to end of initi.1 value of NLS_SOIJ.T parameter. If you want toperform accent -i nsens iti ve COm po riso n, append _Ii I 10 the end of in i t i~ I V" I ue 0 f tlLS _ SO R T' parameter.

Boolean Date Expressions

Boolean Date expressions involve chronological comparisons of dates. Cbrcnologica) comparison of dates means the more recent date would 00 ccnstdered as the I~rge .. one between two date>. for exa mple, consider two DATE va r i ab las d 1 and d2 in the fo II ow; ng code snl ppet

Urlletlcrrocht ich U<3Scnulzles Blld

In this example, since d2 is more recent [han d L, therefore d2 is greater than dl which results (d2~ <11) exprasskm into TRUE: vil,l'ue_

NofI.

UrheberrocnUlc h geschlltztes B Id

Conversion between dltterent types may happen it it makes sense, ~U5QL supports both implicit a nd ex p I i ci I COn vers i on. Let's han d le I he conversi on between di ric ren I da ta types of P USQ L.

Datatypes. conversion in PVSQL

There is a. need of CO nversio n fro m one dat a type 10 anothc r so I hal yo u can access and rna n i pu late res ultant va ri ab I e. For exam pie, bi na r)' row rd is CO nverted i n 10 cI'J'J C ter row i d by PlJSQL engine .0 that user can easily understand the location of a particular row. Thete are two I vpes of convers i 0 ns=Expl lc i 1 co n vers ion .'\ n d Imp I i ei I convers i on.

Explicit Conversion

To perform conversion from one data Iype 10 another data type by user, PUSQL provides bullt-In functions, For example, functions TO DATE: and TO NIJM.Bt:R are used 10 convert CHAR value to a DATE and NUMBER value. You ~,n study .,cctio~ Conversion Functions of Chapter 3 of IIri5 boo k for "II typ'" 01 co nvers i 0 HS.

Implicit Conv(Jrsion

PUSQL automatically converts one data type into another data type when conversion makes sense and ls logical. LiSiing 2_B show, a case of lmpliclt conversion.

Listing 2.8: Using implicit conversion

This example firsl stores dale value into charvar l variable of VI\RC~AR2 data type and assigns Ihis variable to da Ce 1 variable of DATE: dala type. Then, it "s,igm cia t e 1 variable to another charvacz variable of VARCIIAR2 data type. Both ella rva r i and charvar2 variables are displayed to see whether they store ihe same value.

When you execute listing 2.8 on iSQl'Plu5, il shows the following ou-tput

The output shows both tne variables containing same dato 2B~D tC-07. lmpllclt ccnverslon mav .1'0 happen when you 'tore values into database columns. See Table 2.7 for all implicil conversions between diffe,ent deia lypes that PUSQl supports.

45

-

-

---

-

-

-

-

Table 2.7 lists all standard implicil conversions where cross sign(X) indicates conversion between corresponding datil type (represented by rowl' into <I data type (represented by column). Implicit conversion also depends on values that are stored in variables, For example, if you stored '010 n d a y' in CHAR va riable, PUSQL ca nnot co nvert it into DATE va lue,

Summary

In thls chapter, we learned about:

a Block Structure of PUSQL program. which consists of four ,ection,_block header, declaration. execution, and exception.

Cl Various different daratvpes available in PUSQL, such as Number. Character, Boolean, LOB, Date and lime, and sub lype. with their syntax and uses.

IJ Lexical units in the program, such JS delirniters, tdontlfiers, Literals. and Cornrrents,

IJ Different types of operators, such as assignment arithmetic, logical. comparison, concatenation, LI K E, a nd IN.

a Various PUSQL Boolean expressions.

a H ow to ha nd I e conversion between d lfferent da la types im p lid (ly or expl idO)l-

46

U rhcberrec htl lch gesc h (jutes M ate,i"

U t h eoerrecrn l.c h geschulZ tes B Id

U rheber reo h IIle h gGS C h utztes Maieri"1

Function, are important port of any programming language, A function is a block of code that I~'ke' values. such 0' Siring, char, number, and date, as argument and g,ive, the oUlput according to its functionality. Using functions in a program enhances Ihe efficiency of the pro!!""m; since )'0<1 C"" simply call Ihe required [unction instead of wri'ling the ern ire code 10 perform aspecific operation. For example, if you want 10 calculate the ienglh of a Wing, instead of writing long programming code. you can only U50 the LENGTH function provided by PUSQL, F~!nClions c~.n be divided inra two categcrles, Buill-in and custom or I.IS-€: r-defi ned. Various programmitlg languages, such as C, and C++, support Built-jn functions Ihal simplify Ihe work of a programmer by reducing the code size, Similar to these programming languages, PUSQL also supports Built-i n functions thol CJn be used directly in a program for performing a specific task rather than writing a long code for that task,

PUSQL provides 1'01, of Built·in functions to simplify the PUSQL programming and provide better functionality, The Built·in funcuons help reduce the complexity of a program by reducing the stze of progr"", code and hiding the logic used (0 perform JOy specific I"sk. For e,~mplc, if you want 10 convert an upper cole string lruc a lower case Itring, you need 10 write the code for performing Ihis conversion, This increases (he lengrh of the program code and make' ihe progmm more complex to ",,,,,age. Wilh PU5Ql Built-in [unctions, you con perform this same conversion by call ing iho LOWER function.

In this chapter, we describe various caregones of Built-in functions provlded by PUSQ.L, which are:

IJ Character lunctions CI Date function,

CI Nu merle fu net ions

CI Conversion iU,I1Ctiol1s

CI LOB end Miscell"neou, lunctions

We wil,1 srudv all these function in detail next, Here we start our discussion with character

iunClions_ .

Character Functions

Character function. retrieve inlormation of a ,Iring and modify its content. For example, the character functions can be used 10 calculate the lenglh of a Siring, convert upper case leuers to lowercase letters, replace a character or a sequence of characters of it string with another specified character, concatenate two strings, and so 01"1.

Character functions. accept CHAR or VA.RCHAR2 values as parameters and return either .rI, number or a character value. PUSQl has various built-in character iunctions_ Some important and widely-used character [u'lClions hove been summarized in Table 3. '1_

$!~~I"-,3:~i¥iJsliL ~ii.,jli:~r~furicJi~;'s a~dtli".!.':d8_ski¥ri~~~- '~1F~~'~'~' ~jltr ......... .__A

Function

Description

HOIUm. !he AS ell •• t"" !h. function.

Melt

48

After a brief description of some of the character functions, let's understand how these function, work. Let's study all the functions given in T,)ble 3. t.

ASCII Function

The ASCll function accepts J chJr"ct~.'r as " parameter and returns the ASCII value of that character. You can also pass ~~ ~uing as ~l par~fnelef but th'is function oilly returns Ihe ASCl I value of the very [irst character in ihe Siring.

Syntax for the ASCllluncUon is:

~'Gt-li~(~in9'e....:(;h.ilracter) ; In this 'yntax:

Q "inglo_cha~act"r is the speclfted character whose ASCII value has 10 be retrieved. Lis\ing 3.1 demonstrates how the ASCU function works,

Listing 3.1: PUSQL program to uSC ASCII function

49

U rhcberrec htl lch gesc h utztes M ateri"

In U stl ng 3.1, we have declared a varia b leg r a d of the NUMBE;R datatvpe in the De cl a r-e sectio n of the PUS Q L b lock. In I he Exec ut i on sect i on, we have used SQ L SE LEeT statement 10 retrieve the value of employee'S GRACiE from the table s a l qr ade where HISAL~30QQ. The retrieved va I\J e is stored in I he g r a d va riable.

Final'I)', we have passed the g""d variable in the ,ASCII function 10 know the ASCII equivalent of the value stored in thai variable,

The outpul of lisli,ng 3,1 is as follows:

Output:

The output 52 is the ASCI'I value of 4. lithe query executes successfully, then there appears a message fiLl SQL p r cc adu r e success fu 11 y comp l et.e d, as. shown in the OUfput.

LENGTH Function

This function accepts a Siring as an argument. The Siring can have spectal characters a. well. This function returns the length of " string specified as an argument. This funclion rei urns NLlLL rather than z c r-c if you pass an empty string.

Syntax for the LENGTH funclion is:

~~~n.a.7.'~""".

In this syntax:

a st r ing_ va 1 ue is the Siring whose length has 10 be calculated. Sec Listing 3.,2 to understand how the LENGTH lunrtion works. lining 3.2: P LfSQ L p,ogrJm 10 use J..E;NG TH lun ct ion

In Li,ling 3.2,lirst of all, we have declared a variable narn of datatype VIIRCHIIR2 in dec l a re section of the PUSQL block Now, in the execution section we have used SQL query 10 retrieve the ENAME (employee name) from the table EMF where EMPNO~78H. retrieved value is stored in variable nam, Next. the variable nam has been passed in the [unction to get the length of employee name stored in the variable nam,

50

Chopltr 3: U,uler5wllairlg PUSQL .B •• ilt-in {uuerions

The output of Listing 3.2 is as follows:

Oulpul:

; -

...

. •. ~ 1"._ .

.. ~.~. ;'

In this OUlput 6 shows the length of the employee name retrieved from the lable EMP.

INITCAP Function

The INITCI\~ function accepts a sl,ing as an input and converts the ,fi"t leuer of every word in

uppercase a nd rest of the words in lowercase I euers. "

Syntax for the HlITC'IIP function is:

N llCM (it!:", n'g;:"val U:.) : .,-'

In this syntax, string_value is the ming in which the nrst leuer 01 each word has 1,0 be converted in upperca,e and rest all in, lowercase.

l.lstl ng 3 _J shows h ow the ! N ! TCAP' fun CI i on works.

listing 3.3: PUSQl program louse IN ITCAP function

In Listing 3.3, first we have declared a variable nam of the VARC~IIR2 dal<ltype. Aile' declaring the variable, SQL SELECT statement has been used to felch the employee name into the variable MOl from lhe table EMF where EMFNO ~ 7876. Ar last , we have appl led the rNrTCIlP function on the variable nam. When we execute the code shown in listing 3.3, the OUtpUI. we get is as 101,loW5;

O"lpul:

~~~~~~~~C~~d~i~ ·sutc~ssful'.Y conp'let ed.

In thi, output you can notice thai the (irst Ie tier of the name is in uppercase and rest all are in lowercase 'I etters,

CONCAT Function

The CONCA'!' function concatenates two strings passed as parameters, Thi, function appends the second string at til" end of first string and then return, the resultant ,tring, If any of the strings passed is NULL, il returns another string as the result. It wi II reiurn NULL if both the string passed are NULL.

51

Syn lax for I he CONCAT fu nction ls:

'CO~CAT Cstd "gl_vl;jU.':Lst"jng2.:.v~Hl.):"':",

In Ihis syntax: stringl_vaLue is the ,t,ing 10 which the str1ng2 value has 10 be appended.

Li5ling 3.4 shows the PUSQL progrom to demonstrate how this function work s, Li sting 3.4: PUSQl progra m 10 U se CO NCAT fu n ctlon

In Listing 3.4, we have declared two variables, nam and nemt , The narn t variable has been initialized with the value 'Welcomes You', After declaring variables, employee name has been {etch ed i 010 111 e nam va ri able from the EMf' ta b I e. where ernp I oyee number is equa I 10 /8 4 4. Finally, we have applied the CONCAT function 10 add both the .sl,ings that arc in variables nam and namL

The output Lisli~B 3,4 is as follows:

Output:

I TURN ER,kI'e 1 comes. You

P"L/SQL procedure successfu'lly coep'leted.

, ~I ••

In the OUIPl'l, TURNER Welcomes You, the [irst string (TURNER) has been fetched from the to bl e and t he second 0 n e (We I comes You) has been declared in th e PUS Q L P rog'" rn. ) n th is w~y, the CONCAT function combines the ,I,; nS5 into one.

LOWER and UPPER Functions

Both these f~ncliom accept , single character Or a Slri~B as a parameter and convert it to lowercase Or uppercase characters depending on the [unction being used, tf you Lise the WW'ER lun ,I ion, th en a II uppercase c ha ra C te rs wi II be converted into lowercase c ha racters, and i { yo U lise fh e U P ~ E R III n ction then a II lowercase c h a meters will be converted into uppercase cha racters.

52

Sy n tax for the LO~IER fu nch 0 n is:

LOWE'IJ rc~a'r>alue·oc stdn!O-v.lue); Syntax for the UPPER function is:

UPPER (char..:.value. or~~str1ng_:"alt.1e) ~ I n these sy nta xes:

acta r' _ 'va 1 u~represent' the single character whose case has to be chsnged, Q stIing_ veLue represents the complete sfring passed' to change the case, The following listing demonst'Jt€ how the LOI,E:R and UPPER functions work. Listing 35: U,ing LOWER and' UPPER functions

In Listing 3,5, first we have declared two variables nam and na'ml of the VARCH.IIR2 datatype, After declaring JII variables, we have used the SELECT'I"tement 10 fetch the DNAME (department name) into n arn from the table DE;~T, where DEPTNO (deportment number) is equal to 20. Then, we hove applied the WI;ER function on the 'Ir;ng stored in the nam variable. and used the SELECT statement to fetch the DNAME into variable narn l where DE:PTNO .is equal 10 50. At last, we have apphed the UI'?ER [unction on the string stored in the naml variable.

Th e OUlpU t, whe n we execute the p rogr. m show n in Li Sl; ng 3.5. a ppea rs as io II ows:

Output:

In this cutout, (he first output (research] is in lowercase letters because of the LONER function, whereas the second OUIP"! (HUMAN RESOURCE) is in uppercase letters. which is the result of the UPPER function.

INSTR Function

This function is used to find (he po,ition of a substring in the main string. This function return, zero in case the substring ls not present in the main string,

Syntax for the INS'I'R function is:

I;NST:R';.(S tr.i "'gLva T u e I s tri ng2 ..... Vil" ue , s tarot; ng..",pos ; to; on. I nth=" res e nee) ;

53

ln thls S,yfl',~>O::

[J st; ring 1_ va lUB ls the main suing in which the position of the sub5tring has to be found. Cl string2_v,., lue i,:.;, the subsmng whose poshlon has. to be searched in the main. 'string.

[J st.ar t; ing_...oos!.. t Lor: represents the position in main strillA (rom which the search has to be starred, lr is In optlona I [.'Ir8~Jm(~nl. II ~iU~J don't SpE.:"Cify the so ::'artinq_posi cion, the search wl Ij stan frwYl the iirst character nfthe main Siring_

o nth_pt~sc"ce represents the nth posulon of the substring in the main string. li'S.!ing 3'(, s'h(,l\'V$ [tow the r NSTR j"unCliul'l works,

listing 3.6: PLlSQL program 10 usc IIlSTR luncnon

In listing J "f), I'ilst we h,:\ve declared L1 v.il'rli',bic p La c of the v_n.RCH.t,,"~2: datatypo, ~nd then we hove felched the :.cc (departmont Iocatlonj iW) that variable irom the table DE?'r where ('].1=: p-rfNO is equal to 20.

Now, rUSTR function has been <"ipplied on II'ie p-Lac variable three times for rhrec results:

C], tnthe nrSl instance, only two parameters=-she main s.tring and substring-hove been passed.

It w ~ I [ '1. hoi 'I the fi rst oCC\J rrcnce 0 f substri n.g i n : he ma i n su~ ng_

el Sccondlv, we ;tK1V~ passed 4 parameters, This linH~ V'ie h~ve added the positinn from where a search for the substring has 10 be starred In the main string, Here the third and fourth parameters are 1,1, which meanS IhJ( Ihe S!~~,ch has 10 be started from tlw f;rsl letter of the strEng and up ro rhe firs; occurrence of tho suostnng in the mai n s(riflg.

o l\l third instance, I he parameter p~l$scd are same as the in second one e:~cept-thj]~ here we

are s(!'.ltching the substnng up ro its 2 nd occurrence in the main string, .

The OUlPUl ot Listing 3.6 is as follows:

Output:

OAl,!.,fo.S l

l

s .L!SQl

In Ih~ ouiput, Y()U cCln see t'hal Iht'r(;!o ,1H! lour results, The fi rS1 result, lJ.A, l-II..ASr shows the departmeru location, 'which we use 41~~ !ht: rn,llin S1ti r1.g in !~liS, iunction. The second result, 2 indicates the first occurrence of ,lhc ';/ ($ub-s!ring) in the main Siring. The third result .is same as

54

U rheberrec htl lch ge5c h (jutes M ale,i a

J:

the second one because of the fourth parameter due to which the substring has been searched up to its first occurrence, In the fourth result, the position returned by this function is S, which represents the second occurrence 01 'A' in the main siring.

functions

are used to trim the string entered a, a parameter. The LTRIM function trims the string from the left side by removing the character specified as parameter in this function. The RTRIM function, on the other hand, tri ms the string from th~righl side.

Syntax lor the LTRIM function is:

LJl9lII-rUDJl9-'!'.l ue",stri os_trillO.

Syntax for the RTRIM function is:

___ ll';ts:.Ifitfii~;;:l u~, s"tr1n9..:tr"lm); I n be I h of th e preced i ng synt,o xes

o st r ing_ ve 1 ue represents the main string, which has to be trimmed.

o s tring_ nim specifies the string that will be removed from the lef! side Or right side of the main Siring depending on the function yo" use. ln 110111 the tuncucns the second argument is optional and if you don't specify the second parameter then all leading (LTRIM function) or trailing (RTRIM function) spaces wi II be removed from the siring.

-. .Ii ..

The foil owi ng I iSI i ng s h ows how I h is fun eli 011 works. Listing 3.7, Using 1TRIM and RTRIM functions

In Listing 3.7, firsl, we hove declared four variables. nan, d nam, nam2, and d narnj , The variable nam has been initialized with a string havlngsorne -trailing blank spaces while the variable nam2 has been initialized with a string, which has leading blank spaces, After thi" the DN1I.ME has been fetched into the d nam and d nem l variables from the table DEPT where DEPTNO ;s equal to 50. AII"'t, we h;ve applied Ihe LTRIM and RTRIM functions on the strings

in different variables.

55

The OUlpUI of U"ing 3.7 is as f6110ws:

Urh berr 111~1l~_' ILiI tes Bid

The output of Listing 3.7 shows four results, 111 the first resull, yOll call see that al'l the trailing SPilC"S have been removed from the "ring because of the LTRIM fUllclion,

In the third result you can see that alll e ading 'pace, have beentemoved by the RTRIM function. In the seco nd ,,,,,,II, I he depart men I na me h Urn a n r e5 011 r ce h. s been I ri m rned from the I efl 'ide because of the use of the LTRU! function; and the fourth result shows that the string hum a n resource has been trimmed from the righl side.

REPLACE.Function

Thi s fu nctl on rep laces a 1'1 th e occu rrences of a substri ng with the repl 0 cernentsubstn ng Imm the main string, This function is very uselul when you need 10 search and replace a particular sequence of characters with any other sequence of characters.

Synla,. for the RE PLACE !unClion, is,

REPI;ACE: (st.tlnQ_valu", .t~1."g_value_r.p. r.p"string):

In rhls syntax:

o stdng'_value represents the main string,

o s~rJ.ng_v .. lue_[ep represents the stri,ng Ihol 1>.1510 be replaced in the main Siring,

o ~ep _ St1; ing represents the string with which replacement has 10 be made. If the parameter rep_string i, not specified then this lunctjon 'imply removes the s trin<J_ va 11]~ _rep character sequence from the main siring,

Lisjjng 3.8 shows how the REPLACE function works:

Listing 3.B: PIJSQL program tOU5C RE ~LACE funclion

Ud I>EJ", cililici. G sci" I ztes BI1d

In LiSling HI. we hove decl~red 0 variable phc of the VARCHAR2 datatype 10 storethe LOe (Iocalion) of the depMmel11 [etched from the table PO:PT where Dt:PTNO is, equal LO 30. Afler declaring these variables, we have used rhe SELECT statement to fetch the LOC. and .finally we how appl ied the RE PLACE function on the wing .fetched from the table,

56

U rl eborrec h II lc h .iesc II [,Ides Mil eria

Chl'1pl(,"f .1.' UjJderr.lomiir!8 PUSQL Built·in Fuuf/iorrs

The output of Listing 3.6 i5 a, follo';vs:

Output:

Cl-IICZGI)'

p YSgb"iP ro<;,edu roe : sue ces So flJ 1" 'f comp 1 a tad •

In the ouiput of Lisling 3.8, you can see that 'A' in CH lCAGQ has been replaced by 'z' and the output becomes CH ICzGO. CH ICAGQ is rhe cmplcyee Iocation that h as been letched from the EMP table,

SUBSTR Function

The SUBSTR tunctron felchc:s the substring from ihe main Siring, This tuncuon is the most widely used function in PUSQL.

Syntax for the SUBSTR funclion is,

SOSS1"Rh{str.lng_value, ster-tcpos , len_substr); In this syntax:

Q 5 t r in9_ val ue represents the main str-ing in which a substring has to be searched,

a s t.a rt _P03 repre,enls the posltion in the main siring from which the substring has 10 be extracted.

Q len _ subs t r- represents the number of the characters 10 b~ felched from the main string.

The len~substr option is optional; if you don't specify it, this function returns the whole Siting from the 51arting posinon of the whole ,lrin8'

Listing 3.9 shows how this function works,

Usling 3,9: PUSQL pmgral11 to use SUBSTR function

In li,ting 3,9, we have declared a variable nam of the VARCHAR2 data type, and then the E:NAME (employee name) has been [etched into that variable from the table EMP where EMPNO-7 84 4. At last, we hove used the SUB$TR [unction on the lelched 'Iring.

The output of Listing 3.9 i, as follows:

Output:

URNE'

eLLsciL"p(ocedur,e successfully CO<i1pl "ted,

57

The strl ng rei ched fro rn I he ta bl e ;, TURN)': 1;\, and accordi ng 10 the para meters pa,~ed in the fun CI ion, it has, to re trieve a substri ng stan i ng r rom the posi I ion number 2. to 4 in the rna i n stri ng_ In the ou tput, URNE, chi] racters U and ;: am the second and fo u rth posi tio n characters, respectively, of the stri ng TU RNE R.

TRANSLA TE Function

The THAN SLAT E; fu netic n "'p I aces a si ng'l ~ ehara cter "I a ti me, Th ls lu n ction rep la ces a character set ina Wing with another set of characters, For example, if there are two character strlngs J 23 and 456, this function will replace the 1 with 4, 2 with 5 and '0 on.

Syn tax fo r the TRANS LA T£ fu ncti 0 n is,

In this synWx

Q s t r i ng value shows the main string in which the character has 10 be searched and replaced~

Q string~value~I"ep represents the Siring which has to be searched in string_ value.

Q rep _ s.t. dngrepresen!£ the siring wilh which the corresponding character of stri ng_ va I ue_r0p wi I[ be rep I aced,

Listing 3_1 {) shows how this function works.

listing 3.10: Using ')'RANSLATE function

Ufh ooorrocml 0 h geschul2 les B Ij

The output of Listing 3.10 is as follows:

Output:

The stri ng fete hed from til c tab le is SALE SMAN. The strl ng5 passed .i nth i 5 fu n ctlon as pa ra meters ore 'SLN' and '18Y' , You can see in the output that s has been replacec by 1. L w.ith B, and til with Y and' we get the resultant Wing as l}\B~~MA Y.

Wi th In is, we h ave co m p leted di 'cuss i on 0 n Ihe m ost common Iy used chara C ter fu nct.i ens available in PUSQL_ Now, we continue OUf discussion with D~le functions.

58

U rl eborrec h II lc h .iesc h [,Ides M "'eri~

Omplor ,J: Unrler,I.",ii"S PUSQL 811i/l"I" [,,,,,Iio,,,,

Date Functions

The date functions allow you 10 rnanjpulate dales, Suppose, you IVJnt to know the number of months between Jny two given dates or need to convert J date string in \0 a VJI id date formal according to your requirement ~hen you must have to write a progr,,"m for achieving the required results,

PUSQL has made these operations simple wilh the help of buih-.in date functiom. PUSQL Buillin date functions accept dale as a parameter and return ,J date or number as ,) result, PIJSQL provides various built-in date functions that help manage date/time for a database. Table 3.2 shows some important dale function"

NEXT_DAY

Table 3.2 presents some important dale functions. let's connoue our discussion by explaining .11 these functions if) detail,

TO_OA,TE Function

Thera _ DlITE fu ncli on accepts a stri ng and a forma! pa ra meter "5 a rgu rnents and converts the string into date according to the formal parameter,

Syn~'x for the TO-l)I\T,E funClion '15:

;.;.:

In this syntax,

D string_value shows the string that needs 10 be converted into a date.

D ,ormat_para represents the forma! parameter according to which the string_value will be convened into a date. The following table (Table 3.3) shows some of the format parameters, These parameters can be used in varlcus combinations to get the desired result.

59

U rheberrec htl lch ge5c h (jutes M ateri"

Paramete,

Desu,ipti. n

R.p .... nts "I! 4-<1i~"" of iii. v.a, in tho .. ,uk.n' date,

Hop, •• ems 1 •• 12.digit althe Y." in tho , ••• IIM! dat •• Rop,aunlS tha month in numenc form. For .""mj>l., Jan 3$ Dl.

R.p' .... to tho mo",h in abb'."'ut.d form. Fu, ••• mpl., July 0$ Jui" R"I"."IIIS tho dav.

MM

MON DO

LISI ins 3.1 I shows how the 'TO DA'TE [unction works: l.isting 3.11: PUSQl prow",", 10 use TO _D~.TE r""c:lton

5Q L> sr r 5 E.RVEROUTPU'T mil Oi:.CLARI::

e,_oat VA~CHM2(?O)," ·1,1568· ; BF.GIN

m~~5~ouTPUT. P'lfT~!..INE(TO:JlATe( c_dilt;. END;

!

In li,ting 3,! r, the variable e da t or the VARr;HAR2 datil!)'pe has, been declared. It is then initiiliz<,d with the 'Iring '121568'. fit 1,"1, the To_N,~E function has been applierl On this V.i..ut.able.

The output of L isring J, 1 I is as follows:

Output:

Pl/:SQL.. procedure succe ssfu'l l y coep 1 e ted,

In r!-:u:~ precedillg {Jl111}ul', ~J[)U can sec Ih~t Ihc fl",~~t.!' fOE md~ or rb~ $I}~~:if[c(t ~lJi,I'ig has ~ht-lnged.

TO_ CHAR Function

This function oIccepll ,1 number or ., d,)le "long with th" fO'n1Jt parameter and converts it in 0 Siring ncccrdmg to thc forrTI!)t parameter specified .1$ i) 11 argument.

Sy~ld' for the 1"0 _CHAf< functio", is:

TO_(]t/I,R (val'lj ·for:'j1at~p,~ r-r ],'); ln th is syn tax:

CI vall represents either the mrmber or the dille value

D Format_par represents a format parameter according to which vall will be converted into a strir'lg.

60

U rheberrec htl lch gesc h (jutes Iv! ateri a

Cllaptt:'r 3; Unl'l('r5~lij,rding PUSQL BuiUrjr! Fuuctions

See the [cllowing listi ng 10 understand how the TO _CHAR {unction works. Listing 3.12, PUSQl program to use TO _CHAR function

I~ U,ti'ng 3.12, a variable da t of the DATE datatype and da e I of NUMBER datatype have been declared. The variable da tl has been initialized with some numbers. Then OOJ (employee's dale of joining) has been fetche<1 inlO the variahle da t from the table E:MPLQYEE, where t;_NO-7840. Finally, we have usedthe TO_CHFIR funClion 10 convert Ihe dale and number values into a siring according to the specified forma! passed a, a second parameter in thls function.

The output of l.lstlng 3.12 is as follows:

Output:

In the preceding output. you Can see three results. The nrst result, shows the date fetched from I he ~M PLOY EE table, til e second few II shows I he da re COn vc ned i ow a stri n g. a nd the lh i rd result shows the number that has been converted ;nlO the string.

ADO_MONTHS Function

This function return, a new date with the speclfled number of months added 10 tile dale specified as input parameter. This function accepts dale and a number as parameters,

Syntax for Ine ADD _ MONTHS function is:

AOO,:'}IO:tfJ.HS, ('Valt"lrl...Jion);

In this syntax:

o val shows I.he dale whose month has 10 be modified.

o n _mOIl represents tn e nu mber tha t has to be add ed j n th e month of the V" l. The followi ng I iSI i fig sll OW$ h ow In is fu net ion we rks.

61

Listing 3.13: PllSQL program :0 use ADD_!1ONTHS function

In Listing 3.13, (jrsl we have declared a variable dat, of the DATE daiatype, and then !:OJ h." been felched inro Ihe da t variable from the table iOMPLOY>:E. where E NO~i842. At last, we have applied the .~DD _MONfIlS function on lile cia te fetched from the table.

The output of Lisling ],13 is as follows:

Output:

The firS1 result in the output of lisling 3,13 is the elate fetched from the table •• andthe second result is ihc outcome of the ADD _NONTHS funcuon, According 10 its funCliona,lity four months nove been added to the date fetched lrom the table because the second para meier passed in this function IV"S ~.

MONTHS_BETWEEN Function

The 110NTHS _ BET\-I~EN function compares two dotes passed as paramelers and returns the number of months between the specified doles.

Syntax for the MONTHS _BETio/~EN function is:

MONl}[5._6ETWE:EI< (vall. vall);

In Ihe syn{.1X lor the MONTHS BE'f11EEN f".oction, the vall parameter represents lhe first dale and the val2 represents the second dale. See Lisling 3.1410 understand its working:

Listing 3.14: PUSQL program to use M)NTHS_B~TWEEN function

62

(Iropler 3; Umj"sl.",i1roS PLlSQL Bui/I·I" Fw"lio",;

In listing 3,14, the variables dat, and dat I of the DATE datatype has been declared; then we have fetched CXJJ (employee.s date 01 joiningl into the variables dat. and de t I from the table EM~LOYEE, where £: _NO ls equal to i 84 0 and 1844 for the two variables respecuvelv. At last, we have d is P I "yed Ille do res felch ed Iro m the IJb lei nto those va ri abl es, 10 II owed by the dates passed as parameters into the MONTHS_BEn/EEN function,

The OUtput 01 Listing 3.14 is as follows:

Output:

In 1 he precedl ng output, the f «I, two va I ues show the do tes re trieved f <Om th e t~ b I e ~ nd the t h i rd value shows the difference of the montr« between two dales retrieved from Ihe table.

LASr_OAY Function

This function accepts a date as a parameter and returns the last day of the month On the basis til at pa r arneter.

Syntax for the LAST_DAY function Is:

~.o,;y:rv'l1I;=~,~!!f In this syntax:

c val 'represents the date value from which the la$1 day of a month will be fetched.

Usting 3.15 shows how the LAST _OAY fUI1Cliol1 works. tisling 3.15: PUSQL program to use LAST_DAY lunction

In Listing 3.15, Iirst we have declared a variable da t of the DAT£ datatype, and then, we have fetched CXJJ (Date Of Joining) into thai variable from the table 8M~LOYEE, where £: NO~'844, AI last, we have passed the da t as para meier in the LAST_DAr function 10 know (helast day 01 the month,

The output 0 f Li sti ng 3. 15 is as fo'ilows:

Outpul:

63

In Ille preceding output, Ihe fiN result shows the dale ",lrjCI'e<:i from the r,)hle and the second result show, the date on the last dav 01 th"t month, thatis YI,

NEXT DAY Function

This function return> the next day in the dole to Ihe dJy specified in the date string, This function accepts a date and the weekdav as parameters,

Syrnax for the HEXT_D.'IY function is:

NEXT _);lAY (val, ,,_day); In the pmc~'{!ing syntax:

Cl Val represents the dr.'le siring whose (by value IM5 10 he changed, CI ','j _d a y represen ts I h e week days ; S" ndn y to Satu rcby),

l iSling 3:16 shows how Ih~ NEXT_DAY function works.

Listing 3.16: I'USQL proW"'''' I() lise NRX'f _D.',Y function

ln Lis-ting 3,,·1&. first we h4)Vc declared J. vllri~blc dot of the- Di\TE diltatypc thnt has been used to store I he dale f ore h od from the lab I e em p I ovco, where E ;;O~, 8 ~ 2. N ow I he d a to f etc hed i nto thi, variable would be displayed, onwhlch th" NEXT_DAY (unction will be applied,

The oulpul of listir>g 3.16 is ,11 follows:

Output:

lS-AUG-07 lS-AUG·07

PL/S,QL procedur-e

In the preceding output, you can see the elate on which the next Saturday (second mgumcnl) will r,IL

SYSTIMESTAMP Function

This. function returns the time including fraclions. of seconds and time zone .1c("orrJ'ing to your I oca I dataha se.

Syntax for the SYST !H!;;STAl-l~ nmctlon is:

So YSt1:MESTAMP;

64

U rhcberrec htl lch gesc h utztes M ateri"

This function doe, not require any argumem and its output i ncludes date, time wilh fr.1ction of seco n ds, and time zone.

Listing J, 17 shows how the SY STIMESTAM~ function works:

Listing 3.17: PUSQL pmgram to use SYSTIM<:STAMP function

U rh eoerrccrnl c h qescmuws B Id

The output of Listing 3,17 is as follows:

Output:

Urhooorfacnil en geschulztes Bid

With th is we com p I etc eli SCUss ion on most eo mmon Iy u sed do tc f u net i ons. let" s COn Ii nu a our discussion by ""pl.ining numeric functions.

Numeric Functions

Numeric 1 un ctl on, help you pe rio rm rna them" tlca I calcu I at ions, sue h JS, the tota I 5.) I a ry 01 employees. and counting the number of records in a database, These functions accept anumber a, a parameter and' return a number as the ouiput. PUSQL provide" many built-in numeric functions some of which have been explaioed in Table 3.4.

Description

ABS Rutum. the ebWl''!lO Vlllu;, ul.' ",umbor.

U,I_cb"".."lrtlicl geschOtzte$ Bi ~ Urt berrec It I I h 9 Cl1ullies Slid

rbeb I r Chili h Q.,ohCJtzle. Bi:cl

POWEll

Urhebe"echtlich qescttutztes Bi ~

J rneborr ec tltildl ges c rnnz res B i IIj

U rhebo rrec htlic h qes c h utztes Bi d

U me berr eo htlicn ges c nutz tos Hi Id

Helum'. th.",malnder of 0 •• number divld.d by •• Oiber •• mb.r.

65

Tabla 3.4: Numeric functions

funetion

D.scription

Rflurn. Ih. nu_ 01 .. _ In • lobi. on tho .ba'" .1. qUlry. Ce.\"u!lltes tho so m .f a~ thl .olu .. In In .axpml!lon.

U •• d I. know tho ,ign of • numbe,.

CDUNT SUM SIGN

T a hi e J.4 gives a br i ef descri pi io n abo u I '0'" e of I he i rnporta m nu mer ic fun eli ons, Lei's study them in detail.

ASS Function

The .~8S funClion accepts a 'ingl'e number as a parameter and rei urn, its absolute value. For example, if you warn to know the absolute value of ·15.45. then this function will return 15.45. Syntax for the AIlS lunction 'is:

A"S (v.ll:

In th is s\"nlO x:

o val represent' the number whose absolute value has 10 be calculated. Tho following lisling shows how the ASS function works.

Listing 3.16: rUSQL program to lise ASS funClion

Urheberr»enllroh gQs~h tzies Bid

In LiSling 3.1 B. we have passed one positive integer value and one negalive integer value in the ASS f u netic n,

The output of Listing 3.13 is as follows:

Output:

Urheberrec~t len geschlrt2les Btld

CEil ilnd FLOOR Functions

Tile CE:IL funClion retcrns the smallest inlegervalue greater Ihnn or equal to the value speclfled a, a parnmeton and the FWOR funclion rei urn, rho largest integer valueless than or equal to the value specifled as a parameter. BOlh. the CE:IL and E"LOOR, Functions ~CCCpl" single parameter of Ih e number cia lalype an d work in t he same rna n n er.

66

U rhebarrec h tllc h g sc h utztes Maieri"

Synl~x for the CE LL function is: -=-un~ (vall; " ...... ,_-_=-"'''"

Syntax for the E'LOOR function is:

~':T.'_.

In both syntaxes, val represents the number parameter. Listing 3.19 demonstrates how these functions work. li,ting 3.19: usi ng CEI Land rWOR functions

The outpul of listing 3.19 is as follows:

Output:

POWER Function

This function lakes two values as perameters=e base number and the other number as the power to the base number. The PO~'ER function returns the base value after calculating its power

according 10 the other argument passed in this function. -

Syn tax for I he EOWE:R fu n ction is:

, .::~ ... ~ ,

In thi s syn tax:

o b _ n urn represents th e base n urn ocr.

o p _ n urn represents In e power nu rnber with wh i ch th e base n u mbe r has to be powered. Listing 3.20 shows how (he !'OWER function works.

Li,ting 3.20: PUSQL program to use !'OWER function

67

The output oi Listi I1g 3.20 is as ;0110"',:

Outpul:

1000 9924.36543

P L /SQI". pcoc edu r-e

ROUND Function

The RO U N D fu ncti 0 n a ccepts ci 1h er Q ne or two pa r arne ters. F i rst P,l ra mere r i s compu lsory an d is the number whose value has to be rounded by SOme specific decimal points ,pccif,ied as the second p~l,alll(loler.

Syntax for the ;mUNO function is:

ROON.O (r _nUITl, d_f1um); In this syntax:

[J r _ n um represe 11 ts the n urn be r whi c h h" 5 10 be rounded. T hi 5 para me ter !, comp" lso ry.

r.J d_nlil'l represents the dccunal places .,ccording to which r_nu", will be rounded, It is an optional parameter, ~nd if you don't specify this parameter, then the ROUNiD function deletes lhe n~,lrf'lher:-:. "1:11~r (1E-~in~I;;'11 poinl aml returns the output.

listi ng J.21 shows bow the ROUNO fLJ nction works.

Lisling .1.21: PUSQL p'og"o·, If) use 9-0UNT) fllnction

The output of !.isting }. 21 is as follows:

Output:

16 16.2%

PL!SQL pro(.educe

In [he preced'Flg Ot,lptl1. lheFe are 1\\'0 n:':Slllt$ show- .. ln ~hc fir~1 result, ~II the numbers aner (I eci: rn J I ha ve been removed bet: ,1 U'S{,!" we have nol spec t fi ed I he seco nd l ',1 r.~1 mete I'; a nd thercfo re, it h" s de I Ned n u mbe r5 J iter t.he d eci mal.

In ,hc second result! th(-'n:-· ~rl! oniy lhr(~e- numbers af1er the decimal point; u is because thefunction has retained the numbers u,p 10 lhir{.t ptace ;-Iftcr decunal. as specifiud in the second para me!.r;~ r.

sost Function

The SQRT function .acC(~pts ,1 number value as a p.lr.ame~(Lr ,and reterns its value ;.fte-r doing square mot 01 Ihe v~llIe passed 4iS the .I')4':r~rlleler.

68

U rheberrec htlich ge5c h utztes Iv! aler!"

Chapter J: Uwi.~rslaudiJ!~ PU5QL Buin·!)1 FWKlions,

Syn lax for the sQl<. T fun ct ion is:

In thrs syntax:

CI "_ num is the number value whose square FOOl hal 10 be calculated, This number value should be zero or any positive number"

See the U<ling 3.22 to understand how iI works. listing 3.22: PUSQL program to use SQRT function

The output of Listing 3,22 is as follows:

Output:

MOD Function

The MOD function accepts two pararneters-c-the first number as a dividend and the second number as the divisor, This function then performs calculation on the values passed as pa ra mete rs and rete rns I be rem" i nder as th e resu II..

Syntax for the ~lOD function is:

MOD .• (<hIl""l; ,d_num2); In this syntax:

Cl d _ numl represent s the dlvldend. O d _ num2 represents the divisor.

Usting 3.23 shows how this function works. Usting 3.23: PUSQL program to lise MOD function

69

The output of I.i'li~g 1.2] is as follow5:

Output:

1 1..625

PL/SQL procedure

COUNT Function

This fOIKlion hell" YOli calculate Ihe lllt,,1 number of row. in a table based on a particular query. for example, if you wont 10 know the 1.0\01 number of employees in " labk' or the number of employees having ,.I.ry more than 10,000, then this function GJn be used [or relrieving Ihe results easily.

Synl'" fo' Ihe COUHT function is:

In this syntax:

U COllIn- (col name o r .) Is Ihe method with col name a, its "'gum!"lll. The "01 name represents Ihe column name in which the courn of I'lle 101.<11 number of rows nII~d wililsorne value, has to be found QUI. This function does not count a blank "Ow. The' can be used wh an you IV" nt 10 en leu late (he t01" I n umber of rows i n the ta b I" wi Ih almost one fi II ed entry in €IVery row.

T "ke J Co se lor eXJ "'pi e: ,\ II I h e em p I ovees in an o rgil n i IO lion hJ ve been asked (0 subm it their cell phone numbers by using their online accounts untll 'specified. date. Aner the specified date, the riR d~Pdrtrn-f~nl WiH1tS to know the number of employees I.hat have gh'en there c~!l phone numbers. In: UMt case, you have to specify the column name (in bracket of COUNT {unc~iolll rep rcsen t i n,g the cc II n u rnoer in th e IJblc _ Th i s fu ncb On (he n co u nts III e nu mber of rows hav i n g cell phone numbers and returns the value.

I!:l t.,;b_fl.o:r.e represents the table narue.

Q Co~cli t ion represent; a specific value on [he basis of which the counting wi II be done. See li~!irtg J .24 to understand th~~, function.

listing 3.24: PUSQl progr.1m 10 use CQU~lT function

In tis.ling 3.24, we hi.we used T with the count hJr'iCli[JFi tQ rerrieve the !01J~ number 01 employees in the [able I'.MP.

70

U rheberrcc htl lch gese h (jutes Iv! ateri"

J:

Brtilr-iu Flmc-tio~ls

output of Listing 3.24 is as (allows:

Function

SUM function allows you fa gel the sum of the values specified in the expression as a Syntax of this function is almost same as the COUNT function e)(Cepl that here' does

work.

Syntax for th e SUM lu nctlo n i 5:

(tol_n.m~) FROM t.b..n"",e WEFlE condtt1 on:

In this syntax:

IJ SUH (col_namel specifies the column name (col_name as shown in bracken whose row's sum you have 10 calculate.

IJ tab _name represents the table name.

IJ condi t Lon specifies a specific value on the basis of which tile sum will be calculated.

For example. if you want to calculate th e sum of salaries of those employees who receive 10,000 as salary, then you Can specify this condition with WHERE clause,

listing 3.25 shows the working of the SUM function.

3.25: PUSQL program to use SU11 [uncuon

In listing 3,25, we have used the SAL (employee salary) column name with the SUM function to the total salary of the employees in the table EM!',

output of Listing 3.25 is as follows:

Function

SIGN functlon accepts a number value as a parameter and returns its Sign, For example, it returns 1 if the number is more than zero; returns zero, if the number is e<:IU~1 10 zero; and return, ", if the number is less than zero,

71

Syntax for the SIGN function is:

SIGN (v.l):

In th is syntax, val r~p resen ts the number va I UG. Lisling J.2&,hows how Ihis function works.

Li.sting 3.26.: PUSQL program to use SIGN function

U rneberr eo h len qesc h utztes Bi Id

In the Listing 3.26, first we have declared" variable e ~ s ig n of the NUJ'1BER dill.lype, which has been used 10 store the E~SAL (employee ,,,I"ry) column felched from the table E.MPLOYEE, wh ere E ~NO - 'l B 4 4, We h ave the" passed 1 he em pi oyee sa I a ry retrieved fro m the lab I ~ in 10 1 he SIGN function. At last, we have passed a negative value in this function 10 check the result,

The output of Lisling 3.26 is as follows:

Output:

Ur 1ebw,C!C11 i 11 gesol\ulltes Blld

By this we have Ii nishcd discussion on numeric functions. Now, we continue our discussion with conversion functions,

Conversion Functions

The conversion function, are very important [eature of" programrning language, These funclions are used lOCO nvert on e cia tatype into a not her cia 10 ty pe, PUSQl p rov ides lots of co nvers len [unctlons th~t can be used explicitly in a PUSQl program. PUSQL also performs implicit conversions when you' do not perform converstcn expliCitly. You should per(orm e~plici1 conversions, wherever possible, 10 get the desired output, because sometimes implicit conversion docs not give (he desired output. Tobie 3.5 shows some important conversion luncticrts.

Function

CONVERT TO_NUMBER

It convurts a string lrom on. char.cter lei to '"nallt., .... noci.r iet. II conven" a .tring' to • n"mber.

72

Lei' 5 51u dy th esc lu n CI ions i 11 deta i I.

CONVERTFunction

The CONVERT funClion can accept 2 or 3 parameters, a string val ue, new character format. and old character formal. The third parameter is optional, tf the third parameter is not specified than til is run ct ion use. I" e del" u It 0 haracter '" I.

Synlax for the CONVERT function is:

'COOV~"'r (".1, n...ch~rsa~· o_c~arset); In this syntax:

Oval represents the string value which has 10 converted from one characterset 10 another cha ra cter set.

o n _ char sar represents the character set in which the st'ring value has 10 be convened,

t:I o_charset represents the character set of (he val string value. This is an optional parameter. Table 3.6 shows of the en a racier sets.

tisung 3.Z7 shows how the CONVO:;RSWN (unct;on works" Llstl ng 3 .. 27: PUSQl proS'" en 10 u se CO NVE R T fu ncu 0 n

Sild

73

In l'i5ting 3.27, the variables Co" and cent of the V~J1.CH~,R2 datarvpe have been declared. The varlable ecru has been initialized with" \(ring,afld then the ENl\[iE (employee name) has been H~I,r[e\1€'d; i' n IQ I he va ri a ble co n from I he tab I to ~M r j where El"~ p!'{o =..., 9- 0 o.

After ciccl"'i~g variables and retrieving the EN !>.ME, we have used the CONVeRT function to convert Ihe character set of value passed as parameter with the new character set.

The OUIPUI of li>ling 3.27 is ," follows:

Output:

I co th i S ou II''' I, yo U ~"n see two resu 11.\. I' i rst resu II shows I he er,., p I ovee fl,) me til" t hJS been fetched [rom the da~~lb-rl'Se but i! is. same ,]5 'in the database. Employee name hils nol been converted because the default character SN may {orrO\"" rho same convention 4J'S the character set spcculed as parameter.

Second result has been c'haog(~d ('Kcmding to the new character set passed as third Pdramel~r.

70_ NUMBER Function

The 'rO_NUMBER function accepts L1' ~rring arul a forma! (accordiF\g tu which the string h,jS to be converted iii '!J nurnhcr) as .1. P4tr.)lTIctCJ and returns a number value equivalent to the entered Siring.

5'1jn1ax iur TO _NUMEER function is:

TO_NtJ'I.Ia£~ (va 1'. s~fo:rmat) 't In this, syntax:

!J val represents the s.!ri:n,g thJI h~J5l0 convened in to a number.

Cl s_forlna·treprcscnls the formal according to which the string will IJ.e convened in 10 nurnber.

.,;:

The iollowing llstlng shows hOVLI the 'to _NUMBER functlon works, lisling 3.28: PUSQI. jlfuS'''''' 10 use TO _NU!"5E:R functlcn

74

U rheberrec htl lch gesc h (jutes Iv! ateri"

In Lisling 3.28, the variables con and coni of the VIIRCHA.R2 datarype have been declared. The variable con 1 has been initialize{! with astrl ng. Then the H I RE:DII!E has been retrieved into the variable con frornthetable EM~, where E;MrNO~1900. Finally the TO_NIJt>l,BE;R function has been used on those values.

The outpul of listing 3.2B is as follows:

Output;

Ur!l bcrrecbt i h ~ Sch"lzl s Bil

After discussing the important conversion functions, let's continue our discussion with another built-in PUSQL function. the Large Object I LOll) functions.

LOB Functions

Sometimes. you nt<ly require 10 store Ii les such as im"se files, video files, of very large size, in th e d a taba se, Now the qu est ion 0 rises how )'<'" co n sto re SU 0 h a lorge fi lei n the do t~b" se I" ble! _ PUSQL provide. you with the function coiled LOB that allows you 10 store r; les up to stze of 4GB i ruo th e database, W B has two pa rts one is LOB I OC" lor a nd a nether is LaB val ue.

A database table stores the 108 locator which ls in f.el a pointer to the actual local ion on LOB value. Tobie 3.7 shows description of some LOB lunctions.

D •• ~ri.ptiDn 1 •. !ii_allz8SBFILE, 10111" obl~ 001"", .. 111 Ito daia~'1 tahll,

<

R8blrns empty.lo.alll',.f BlpB typ",:.,

Retti"l .... ptY 10"0"" of CLOB type.

Lei's study these LOB function; in detail.

BFILENAME Function

The SrI !.EN~M~ function, ls used 10 initialize the column of lorge objecl Iype in a database table 10 poi n I an external fi I e or it rete ms (he 6 r n, E I oca tor for 1 h e to B bi nary fil e. Til is fu ncb on accepts two va I u e as para mete" no mel y, th e directory no me and the filc' na me.

Syntax lor the BFILENAM.E function is:

ELf,ILEHAr,'_E (dir_y.murieT f_nain-e):

I n In is syntax:

CI di r name represents a DIRECTORY object 1".1 serves as an alias and: stores the location of the liTe.

75

Urr~b rrechtll II g ,r,h!'Hlt "~\ r rial

Cl f _name represents the file nome that contains the large object.

See the following example 10 understand how sn LEN~.HE function work"

Before using directory alias in the Sfl LENAME function, you must be sure that the directory alias exist, or you need to create il before using it, To create a directory allas, you must have DBA privileges, Sa to creole directory alias login M $YSD13A and then follow the sl':nla< given here:

CREATE OIREcroo;y 'n..,e· AS 'l.ocatio"·;

In this synrax, the name parameter represents the directory alias nil me or the object nome and the location shows the path where the large object binary fi lcs will be 'tared. Let's see how to crea te an d use d i recto ry a li a 5 with B FILENAME fun ction:

CrBating a DirBctory

In the preceding statement, we have replaced the attribute! nome and location with p.Lc and E: \ p Lc t.ur e respeclively. After speciiying the name and location, pres, the ENTER key. You will SE-e the following resu it ,

Result:

01 recrery created,

Now, see the Listing 3.29 to use this directory "lias with BFILENAME function, tisting 3.29: U, i ng B f! Lt:I'IAME run (;t ion

.;1 ,

In the Listing 3.29, first we have declared and initiallzed <J variable pic t: of dill;JI)ipc Sf! LE. Afler that the INSERT statement has been used 10 add the ernplovec picture in the table EMPLOYEE. At last. we have used update statement to change the employee's existing picture wit h I he new pict u re.

Tile output of Listing 3.29 is as follows:

Oulpul:

Pl./SQl procedure succe ssfu'I'ly crenp'lu tnd.

EMPTY.... BLOB and EMPTY.... ClOB Functions

These lunctions initialize a BLOB and" CLOB column in the database table 10 "empty" Column in the table with SLOB Or CLOB datatype can not be set .5 NULL. It must contain. locator that mighl point to empty or filled tOB. Before )'O~ start working with BLOB or CLOB, either to assign it a value in PLlSQL program or to use with SQL I NSERT and UPDATE statements, set BLOB or CLOB column to "empty",

76

Besides inilial:izing .BWB or GLOB, these functions also retum en'ply locator of type BLOB and CWB respectively, Both of these functions can be used with empty pair or parentheses or without P" rentheses,

Syntax (or the EMPT1_ BLOB (unction is:

DIeTY ....!!LqB 0 r EMPn:JLOe 0; Syntax for the EMPTY _ eLOB (unction, is:

E!1!'IY_CLO"B cr~m.::cLoB 0;: ..

See Li'ting 3.30 to understand how 10 set a LOB column to "empty" and how to usc these fu net i o ns wi th SQ L staternen IS.

li,ling 3.30: Using E;~1PTY _ BLOB and E.MPTY _ CLOB [uncticns

In Li,ting 3.30, (irst we have declared two variables of the datatypa BLOB and eLOB respectively, which are also initialized as empty LOB. After declaring the variables, we have inserted these variables in to the database table named EH~LOYEE.

Here you can see the 0 utp ut of Listi ng 3.30.

Output:

QSQ\- proc:echJre 5ucces5ft.l1]yO'cOfllpleted:-r~ :;'.- ~"'i~ ·':"'I)·~.lt"~;I:""·"f-,tiiil~~~

Wilh this we have completed discu,sion on LOB funC[ion,. lei', now discuS, miscellaneous funcrlons.

Miscellaneous Functions

Misce·llaneous functions are those function, that do not fall inlo the category of a particular datatype, (or example, character function falls in the category of character data type, and date (unctions come under the date datatype category. ters study various types of miscellaneous functions. Table J.5 shows description 01 some of the miscellaneous tuncuons.

rt

function

Description

LEAST

IIIIER HID

Rotur •• the nam. of the <""ont .oi:""ni.' \f -~~::'::il

R8hlrns th'e Id, of ",.8: CUR'·!flt aoc:ount.: j ~~""' -, o::~ :~, _ .- :.I

Let's discuss these functionsIn derail and learn how to use them in a PUSQL program.

CREA TEST and lEAST functions

These functions work in the same way but in opposite mann"," The GR~TEST function fete he, the hi_ghesl value from the list passed as an argument, whereas the LEIIST function felch", the lowest value. Both these (unctions accept two or more than IINO values as argoments. There is no I imil 10 pass va lues in both these funClion,.

Syntax for the GRE~.TEST {unction is:

Syntax for the LEAST function is;

l'EAST (va111 val z , valn);

In these sYl1liJ>Le-'50. valn represents the nth value passed. Il implies Ihat you can pass as many value as. you want in this functions. Now, see the following lis.ting to know how these functions work.

listing 3.31; usiog GREATeST and LE_~ST [unctions

In the Li,ting 3.31. lirst the e-_dat vJriJblc of the DATE datatype hJS been declared, followed by fetching H IREDIITE into that variable {rom the table Empl'oyee_ Afler that the GRE::ATEST and LEAST functions have been applied on (he values fetched from the table,

78

The output of the Listing 3_31 i" as follows' Output:

The preceding output display5 six results. The flrst result shows the system date; second' result show, the date fetched from the table; third result shows the highest value among the lists of the value, passed in the GREATEST function as argument,; fourth result shows the highest date a mong the dates passed in I he G!<P A 'I' ~ S T fun eel ion; Ii It hresu II sh ow, the lowest va I ue , mong the lisls of the value, passed in the LEAST function; and the sixth result shows the lowest date among the doles passed in the LEAST funcuon,

USER and UIO Functions

BOlh o( these funcrlons work in the same mariner. The USER function ,is used 10 know the name of the current "CCOUnl, such as scott or 'I'S, whereas the UIO [uncticn returns (he integer value 10 ldent i fy the user. Both these fu nctions do notrcq u i re "ny a rgu men I; it is fo r th ls rea '0 n th a I, the)' look like a variable rather than a function.

Syntax for the USER lunction is:

USU;

Syntax for the UID function is:

L i stin g 3 .3 2 5 hows you how ihesc fun ct ion, work. Listing 3.12: Using USER and' U I D functions

In Listing 3.32, we have declared two variables the u_ser, and u_id of Ihe,vARcHAR2 and NUMB E:R data type respective 1)'_ After tha I (h e S E L EC T staternen I h a, been used 10 reuieve the user name and the use' id into" _ser and u _ Ld respectively from the table EMP, where EMPNO ~ 7900.

79

The OU!PLJ! of U5!i"g 3.32 is shown .15 folio",", Output:

With Ihis we conclode our discussion on the buill-in function, provided in PUSQI.. 'You will now be comfortable with u,ing, these functions. l.er's summarize what we have studied in thls chapter.

Summary

lntbis chapter, we have studied:

Q The character functions. their types, and examples to demonstrate their working.

Q The dale function' and their V~riOLJ5 tYPc5.,,,ppor!ed d;>IC 10"""15, and various ("iHnples 10

show how they work,

L) The nuruertc iunctions ~rld their Irr.>es a:long with examples. a The co nvers io n fun ci ions

Q The lOB, f uncli ons

D Miscellaneous function,.

80

U rheberrec htl lch gcsc h utztes Iv! ateri a

urheberrcetntcn geschu<ztes B,ld

Ur~GbmreohllJCIl geschCllltes Mami"l

In real life, mostly ~~ou neod 10 perform an operation ht1.s~d "" .a condition .. For example, you need toea leu late Income tax for em p I oyecs 0 f an orS') n Il~ lion . For th 'S, you rn u<I app Iy different formulas for "akLli"ling income tax based on their diff"Jenl salaries and diffemnt filing status, U5u~lIy, (),(>{:ution ol ~ PUSQL prow" 11'1 proceeds frorn top 10 bouom except no control srruciure comes in between, Similar 10 other high level structured I~nguage.l C, C++ or leva" I'USQl also provide, various control structures to deviate the sequential now of execuuon of PIJSQl progrJm dependiF\S upon the condition>, execution part of PUSQl program repe"wdly li~~ a specific condition is satisiitxl .. lnd unrondltionally jump to diffGrGnl parts 01 PUSQL program. In other words, these control structures organize the f'lU\IV or execution 'Or a PUSQL program, This chepter discusses ~H types of control ,t,ucture, and explains each of them in details with examples. LUI us study various control structures available in PLlSQL

Describing PLlSQL Control Structures

Control structures Me one of 1T,,"n PUSQL extensions to SQI.. Control structures lead to we'll. structured progr.ln,,,,ing which helps developer, 10 structure tbc flow of control through a PUSQL prog"o"', Each corurol structure has only one ent')' and exit point. Control structures are broadlv divided into three main '.1.'egori~~s~

Cl Conditional conuol structures

Cl Ileraf.ivp control structures

Cl Seq lien tia r co 0 tro I 5 tructu res

tet us. €'>.::r)lain them with the ~H"!r 01 nO\'lch:ir~ di~gr(lms.

C-(l"dllll~I"I",1

)

19, j

:5e:l:;.erJ:l;:M

I

§5

F;g.PUSQl.4,1

Fig. PLISQI.A, 1 consists of one flowch~rI cor"esporodi"2 10 each control strucurre. E,1(1\ H~CI1'.lngu;lar box in thc:!'Sp. llowcharts represents a ~('I ot PL/SQL statements. The selection structure> starts from telting a condition and execute, only one set of statements occording 10 the value' of condition IT or Fl, Usually, condition is either Boolean v~'iable or an expression which results into Boole.1n value. The i~e.l'fHi()ll structure executes the !;cl of statements nepf.'tilhle~y until condition evaluotcs to true, The sequentie) control structure executes the set of statements sequentially,

ThHY@ suuciures are represented br the ser oj" PlISQI_ statements such as 1 F-~n-l EN-t.LSE, CASE, rnR- LOO P. Ii):; i LE- LOO P. ilfld GaTO_ tct us now study Cnndit~on.~.I, Control Statements.

82

U rheberrec htl lch ge5c h utztes M ateri"

Clro"l" 4: Uud".lmrrii"g "USQL COI!!ml Sima",,,,,

Using Conditional Control Statements

Conditional control statements facilitate us to take alternative actions depending upon conditions. Conditional control statements include If-THEN, IF-THEN-ELSE, IF-THENE L S E IE', a nd ell S E statements, Three t F sta ternents exec u te a d iff ere nt ,eq ue n ce of sra ternenrs depending upon the value of condluon. The ClISE statement is nothing but simpler way of wrilinE IF-THEN-ELSEIF statement. The CASE statement also execute, efficiently in comparison to If-THEtJ-ELSElf statement. Let us now study each statement in detail.

IF-THEN Statement

The IF-THEN statement is a, basic IF statement. This statement executes" set of statements when a condition is true. The general syntax of I r-THEN statement is a, follows:

tn this syntax, the condition between If and THEil either eva luates to TR.UE or fIlLSE_ If it evaluates to true then only the block 01 state rnents between THEil and END will execute,

II condition involves Boolean variable, we can simply place the boolean variable in. between I, and THEN keywords as it itsell ls either TR.UE or fAL%_

let us create an example which calculates how many hours an employee 'pent during overtime. See Listing 4_' which IhOW5 the use of I ~-TH.£N statement,

Listing 4.1: Using IF-THEil statement

Declaration section declare, and initializes two variables Hour stro rked and OverTime 01 tlUHBER data type. The I r statement checks whether the number of working hour, is (denoted by ~01JrsWorked vartable) greater than defined standard for number of working hour, iSJ and then, proceeds 10 calculate ove r-r Lme if condtrlon is TRUE. The PUT _LIIlE method 01 DBMS _ OUT~UT' package is used to display OverTime On 'iSQL ptus_

Here veu can see the O"!PUI 01 the Li'ting 4_1

Output:

,..---lfoVc. spent in overtime ~,'4~~.~,~:;-i;1:E!"'c",;'7.; '''~'l,(.-~~!l L.--.fb/SQ!l Rr::m;:edl.U:!: s~(:cessfu1,ly. c9~pJeteci~~.,t,~ "":,")~ ..... '~;~' . ,",,:::.~. .~'~~~~~1f

83

After executing Listing 4.1 On 'iSQl Plus console, YOll will get the output as 'Houz s "pent in ove ~time = 4'. This message contains number of hours (4) spend in overtime 'by a person. Upon each successful execution of JOy PUSQL program, PUSQL cngine also display. PL/ sci, procedure success full y. completed message.

If-THEN·ElSE Statement

The IF-THEN-~LSE statement', functionality Is sirnllar with eilher/or English language sentence, The I f"-THE:N-ELSE statement is lillie complex than IE"-THEN staiernenr. II also executes another sequence of statements if condition evaluates to fALSE. The syntax of IFT H ~ N - E LS E statement is as follows:

Urreoormchtllch gesCh012tB8 Bi d

keyword. am executed based on condtuorrs value (TRUE or l'"l'lLSEj.

We now extend the same example as covered earlier in section IF-THEN statement by i ndud i ng ELSE clau se, See l.lstl ng 4.2 whi en snows use of I l'" -T H EN - EL S E: statement,

Listing 4.2; Using 1, -'~HEtl-E;LSE statement

U rnebc rrec htlic h ges G h utztes B i Id

H ere, ELSE d a use m ea ns tha tempi oyee has not worked for overf me in" n arga n izat ion. I n the preceding lisling, Zero value of OverTime variable represents this.

Here you can see the output of the l.isti ng 4.2.

Output;

,~~~on, doe.!i~,ot.\iJ?l.k·f?r b~er:"t;fI"fI'!, _ J-' P.l!.sQt rooed4[e3tu«e,.:;;f"HY c"'1!plet"e~.

Afier execution listing 4.2 on SQL 'plus console, yo" will gel the output as ~e z scn does n.ot wor~ ~or eve r t Ime in the console, This output comes since HoursWorked variable initialized 10 B which is standard for number of working hours in a day.

84

Ci"pl", 4: U,uJer<lmuJiJ/$ rUSQL COJ/lwi Slmctmos

IF·THEN-ELSEIF Statement

It is the the most complex If statement OUI of available three .I F staternerus. It is used when J PLlSQL program involves more than IWO condluons. for example, you can use this statemem 10 create menu which hove many option, but use of this statement is deprecated, A, this statement makes code complex and also doe, no! execute efficlently. The general syntax 01 1 f-THENELSEI f statement ls a, follows:

In this syntax, ali condition, such as conditionl, cond t t1 on 2 are mUlual:ly exclusive which means more than one condition cannot be true at a time, Here. block of statements associated with TRUE condition are executed, You con avoid using this complex I f statement since from Oracle 91 Database Release 1, another searched CASE statement introduced which performs sa me purpose.

We are 3ga in extend in g the exa mple to i ncl u de ,E LS,E I f d a use. See Li Sli ng 4.3 wh i ch shows use of IF-THEN-BLSE I F statement.

Li,ting 4.3: Using rf-THEN-ELSE. I ~ statement

In this llstmg, we use two different SQL command" ~ROMPT' and I\CCE~T. The ~RO~[PT command here used to print name 01 program On iSQL 'Plus console. The ACCEPT command asks user to input the value of variable TotalHo\lr s. Declaration section assigns value input by user 10 HoursWor ~ed variable and also declares a LessT ime variable of NUMBER rype. The

85

ELSE If clause of this program will execute and display the value of LessTime variable if an employee works for haul'S less than 8 and leave office earlier due 10 some valid reasons,

Here you can see the output of the Listing 4,3.

OutPUI:

Urhebcrrechtllcl !l schurzte Bi d

After executing Lisling 4.3 on "iSQL Plus console, il asks user for number of hours, In this example.Jet's enter value 4 and press En tee key to execute remaining part of l.isti ng 4.3. The output displays the text written in prompt which just shows the purpose of program, The next two lines in output shows that second I ine of Listing 4.3 now initializes the HoursWorked variable with value entered by user, Main message in output is ~erson leave offi<!e earlier by 4 hou rs which contains the number of hours (4) by which person leave office earlier,

Using CASE Statements

CASE statement let you to choose one set of statements 10 be executed oUI of many set of statements, Oracle 9i database release 1 and its upper versions to support CASE statements, Let's discuss different CASE statement in detail,

Simple CASE Statement

A simple CJl.SE statement consists 01 all expression and blocks of PUSQL statements; where each block is associated with a different value. The values of the blocks are specified in the WHEN clauses, The expression in the CP.S~ statement may also contain function calls. Expression's value shou Id be of the CHAR, VARCHlIR2, or INTEGER Iypes. II cannot be of lhe awe, eE'ILE, ohject type, record, Or VARRAY data types. When you execute a given expression, the expression's value is compared with the values specified in the WH.>;N clause. Then, the set of statements associated with the matched value are executed,

The ELSE clause is optional in CASE statements and is executed when no WHEN clause did not execute. If you do not sl,eci'y the ELSE; clause, PUSQ~ inserts the ELSE RAISE:

CASE_NaT_FOUND clause into the CASE statement '''I default. This clause raises the predefined Exception CASE _NOT_roUND,

Let's create an example which explains the meaning of grade symbols to student by using CASE statement. See Listing 4.4 which shows the use of CASE statement.

Listing 4.4: Using simple CASE statement

urheberrecrnrch g~sc~uI2tes Bid

86

Urh:bcrrn'hthch eschutz: S ~tircri"1

C/"'pli'l 4; Uw/m,ra"di"g PUSQL ControlSlm,rules

Th e g r a de variab I e, w h i ch can store si ng I e cha ra cter, stores I he "ppe rca se cha r a cter en tered by student. When PUSQL en gi ne comes across ells E statern ent, it eva I ua les \I t: ede variab I e and compares it with values mentioned in WHEN clause till a match 'is found, Then, statement assoc iated wi til rna tched W HE N' cI" use execu tes and d i spl ays the me. n i ng of gr ade entered by a student,

H ere you ca n see the au tp ut of the U st; ng 4.4, Output:

After executing Listing 4.4 on 'jSQL Plus console, it ask' student 10 enler a grade in uppercase. In this example, let's enter grade A and press Enter key 10 execute remain ing part of l.lstl ng 4.4. Output displays the text written in command PROMP,[, which just shows the purpose of program. Main message in output is Grade A means E~cellenL ~erformance. This message i merp rets the mea ni ng of g ra de A to studen tin te rms of pelf u rma n ceo

~

r-----------~~~~~~~~------~--~--------~~~~~

CASE st.temi;nls can also b<;. ~bele<l and I.~, ~pp~Pr!o!e!CfSE k~rd.!'1 ~'We"!"'1L

Searched CASE Statement

The sea rched CAS E statement (0 ns is ts 0 fbi ocks of Pl.lSQ L statements and eec h block is associated with one boolean expression. Block of statements associated wilh expression which results into TRUE value is executed. Note that searched CASE statement does not include any expression, which COmes immediately with CASS keyword in Case of simple CASE statement, Let's perform the same example of grading student", performance but here student will enter hi' marks and corresponding conditions in WHEN clauses am also different. See U,ting 4.5 wh ieh sh OwS use of sea rch eel CAS E sta temen I.

ti 51i ng 4.5: U, i ng sea rc hed CAS E sta teme nl

87

\Ne assumed thaI studcrn can get maximum of 100 marks. Note the diflerence between conditions me'~tior)ed in "~i-LEN clauses in l[~ting 4_5 and those in ~,lilE:N clauses ot' listing 4_4. These- conditions arc Boolean expressions: made 'up of using relational (>=1 <=) and logical operators (Yl1ld). I'll searched c~s!: statement. condition evaluation also happens in I':H~N clause, Here, you CJn sec the output of the Li~li'-'g '1.5,

Output:

Alte r exec LI ~ i rlg l is.t j r~g ;:'1,5 0 n e i SQL P I us-console, it as ks 5.111den t 10 en to t ma r ks represent ed by Sivl",kl variable. In this example, lei', "'''Ier I he v"ILI~ flO and then press Emer k~1' 10 continue the execution of remaining portion of Li5hng 4.5. Output displJys the text written in com,-"""d rRO~IPT which just shows tho purpose of program. Main nlCssdge in output is St.uderrt at. tained Grade A On the basts of his marks,

Th i 5 SC-C t i on de mo rlst:r~ res I he \J se of sea rc h ed C.~ S E ~1.; Ie men t i F\ C:!I se wh en there :"Lre more 'l htl n three condiuons present in .logic of " I'LfSQL progr,lnl.

Using Sequential Control Statements

\'Ve have seen control structures which allow S€'-t of statements to eX(:;'i.:\.II~~ only when '5Gn1P condlnon i'S TRUE. PIJSQI. 1,1150 'Supports two more statements. GO'TO 1:HHJ NU!.,L which do not need ,)n)f condition to execute themselves, Lel us discuss thorn in detail,

88

U rhcberrec htl lch gesc h (jutes M ateri a

Ch<'pler 1, U"derslm,diuH PUSQL Conlrol SI",clrr'15

60TO Statement

The OOTO statement used 10 transfer the flow of execution in PU$QL program from one statement to another statement directly without ,any condinon. The syntax of 0010 statement is as follow",

GotQ "i1aDe..lnllll1e;?:-.Q'._ '~

.~.

Lebe Iname is the name of label present inside PlISQl program, The labels are cleated by using syntax «label name». In this syntax, surroundlng angle brackets act as label delimiters.

Wc take an example of checking whether entered number is prime number or nOI 10 show you th e use of G8TO staterne nt. See l.isti ng 4,,6 for 'Use 01 0010 statement.

Listing 4.6: U,ing 0010 statement .

Th e ACCEPT command asks 'USer to enter ~ number of INTEGER dam type. Declaration section assigns value entered by user to n v",iilblc and also declares a variable ms q of VARCilllR2 type, The execution block checks il any of divisions of given number by 2 10 inleger tless than rounded value of Square root of give~ number) returns any reminder. If remainder is 0, then the number is not prime number. The loDD function is used lor g~~i'ng the remainder. In case of nonprime number, 0010 statement will execute that transfer control to label named clispl"y. Neext statement to this I abe I outputs the mess"se ,m S9.H ere you ca n ~ee th e ou tpu t of the Li sti ng 4.6, Output;

After executing Listing 4.6 on ·iSQl Plu~ ccnsole, it asks user to enter a number. 10 this example, lei" enter value 991. Output display, the lex! written in prompl which [ust shows the purpose 01 program. Main me"oge ,in output is written as '991 is n prime numoe r".

89

Now, check Listing 4.6 for non-prime number. Here you can see the second output of Listing 4_6_

Mler execuling Listing 4.6 again. let's enter non-prime number such as 990 end pre" ENTER kev, You wi II get 990 is NOT ~ prim" numcar as output.

There ore some limitations of C',oTO statement which are i1S follows:

o Co n not tre nsle r CO n trol to label presen tin side the n eSI_c><1 block.

o Cannot transfer control from ouislde an I ~ statement 10 a label msrde this IF statement.

o Cannot Iransfer control from an I," statement 10 a label inside another I, statement.

n CJMO! be used in EXCEPTION block 10 transfer ccrurol to an)' p"rl of PUSQL program_

NULL Statement

The NUL!. statement itself does nmning but transfer control 10 next statement, In case of certain statements such as 1 rand EXCEP-rION block, Ihere should have ill least one executable statement for compilation, we can use NULL statement here, Note Ihol NlJLL statement and boolean value NULL arc not similar. They are used in different contexts.

ters create .10 example of increasing percet'ltag~ of cornmtssion of an employee hayjng designauo» Sales Persun 'lnd ernpluyee id equals ,10 102_ For other employees, we need nOI. 10 pe rform "ny act io n. See Li ,I i ng 4 _7 lor I he use 01 NU LL sta te 111 cnt,

Listing 4.7: UsinS NlJLL statement

DeclarJtion section declares a Job variable of VARCHAR2 type and EmpI d variable of NuMBER type. We initialize Empld to 102 on which basis the SELECT INTO query is, made. After gelting designation of employee into Job variable. I r staterncrn checks whether deslgnation is Sales Per s cn. The UP!lATE query inside I'" statement multiplies commission percentage (denoted by camm) by 2 _ The ~!'SE clause meant for other employees. we use NULL staterneot hme 10 show no action.

Tni, example operates on a ocnu s table having one following record.

90

Here you can see the output of the listing 4,7. Output:

POSQL p-rocejttJre_sJl~~Mf,u;N:F\~COIIpleted./ '~:-:.i··~~f··· .:'::~--:~;"3'.l.~':', ' .. '.~~_"'_).:.

After executing Listing 4,7 on 'iSQL Plus console, you will get message ·'rLI SQ~ p r-o ceciu ,e successfully comp Ietied'. beeul,e the following query 10 see whether the record is u pda ted or not

~ 'r v .. ~ .... ~;~,.:.;,. ...• ~' .. ;

Here is bonus table after execution of the query. Note that the val ue of percenlage of commission (denoted by ,,"0= fieldl changed trom 10 to 20.

The bonus table after executing Listing 4,7 on iSQL 'Plus console will be as follows:

.: ....... " .': .-'>.f:.~ .,"

.~~~::.-. ..

i ~

Here is another code snippet which uses NULL statement with EXCEPTION block:

In this svnta x, when divide by zero exception occufS,roliback operation is performed, The ROLLBACK statement cancels the effect oi previous transactlon. For Jny other type of exceptions" we use NIJLL statement which means do nothing for the", exceptions.

Using Looping Constructs in PI/SQL

PLlSQL supports various types of loop, to iterate portion of program for many times based on some condition, However, JS a best practice, you mUSI write the type of loop best suited for J specific requirement Dtfferent type, of LOO P statements are as follows:

u lOOP

a FOR·LOOP

a WHILE-LOOP

Let us discuss each LOOP statement in detail,

lOOP Statoment

The LOO!' SI,; ternent is ~ simp I e type of loop an d 'pee ifies 1,11<11 the spec i fied part of the p rOS")n1 is iter,,(e(1 Iill the specified condition evalLlal", to true. This statement hegin" with the LOO!' keyword and end, with the Et'lD WOP statement. The gene,,,1 syntax of the wo ~ statement ls as follows:

91

U rheberrec htl lch gesc h utztes M ateri a

In this syntax, ~el of statements are executed and control ~g.\lirl tr,j):nSler!; to the beginning or loop. YmJ can ~J~i2' other clauses with the WO ~ 'Stalcmenl to specily conduional iteration of the prograln block, For example, you can use the EXl T ~!nd E.XrT-V1;H~N clauses to' specify the given, condition •• as described next.

EXIT State meat

The EXIT statement used to fini'!' loop without on)' condition. Wh(m this statement is executed, loop finishes and control transfers to next statement after the loop. Note thar the E:X I T statement on ~ y wo rks inside J loop.

EXIT·WHEN Statement

The E:n T - 'dHEN ,W temen t <)1,0 '" n ishes the loop bu I when spec i fi ceo n d i t i on i, encoumered, \IVhen this statement i~ executed. condition inside N["iE:~ clause i~ checkp.d, lf thls condition is true, loop f;nish~1 and control transfers 10 next \Idl~",enl "iter the 10,,1', There should be one statement present i"li<ie 11'1", loop 10 chong" the value of condiuon, We con also ~5C I F statement in place of EXI1"-rAiEE.N statement as explained in iollowi ng example:

IF nutlll > 100 'THEoN f'X1Tj E~D[F1 E_X.IT WHEN num :> lOOj

The EX I 'J:'~fdHE.N statement is simpler than .I F statement in this cxarrplc but both perform same ope ra I ions,

We rake an example or inserting complaio; ids to cCltlpla 1 n t.'7i t.';lhre lI.5iF'Ig LOOP 5~Jrcmc:nt. See Listi ng.1 ,8 which lise' wo!' statement.

Listing 4.R~ USiflg lOO P starerneru

The ] NSERT query inserts the following in cv"'y iteration of the loop; !U comp l a in cr d, which is. same as the loop counter

!l Description, which represents the siring value 0:0 be added Lat e r

tf the value 01 'i ls g.n~4Her than lfu:: f~l"'Il(.;'H.;."'{l valm-. the :EXIT i'NHF.N statement completes theloop,

92

U rheberrec htl lch gesc h (jutes Iv! ater; a

Here you (an see the output of Listing 4.5. Output:

After executing Listling 4.8 on 'iSQL Plus, the console asks user to enter" number on which LOO P statement completes. In this example. let's enter the value 3 ond press Enter key. Output di splays the text w rltten in com man d PROMPT w h i ch j us I sh ow, the purpose 01 proS'" m. Yo u can execute the following query 011 • iSQL Pk" console to determine whether loop odds three rows inlo complain r s table or not:

SE[ECf *.:FRO!flC¢ll'plain~.;·'.

The comp Le i nt s table after execution has followlng rows:

This section illustrates the use of LOOP, EXIT and EXIT- WHEN statements.

FOR lOOP Statement

Th e ro R WO P SI a tement i tera res I he pori iOl1 of PLlSQ L r rogr am for known n umber of I i mes. The genera,l,yntax of FOR-lOOP is given as follows:

In this syntax, the FOR-LOO~ statement uses double dot operator which is used 10 ,pe<:ify the range of counter variable between lowerbound and upperbound, This loop iterates the set of statements by LIppe r-bo und - Lowe r bound number of limes. Both lowerbound and upperbound of loop should be any out of I iterals, variables and expressions resulting into n umbers. a III erw i se P USQL arise VA LU £ £ RRO R predeli ned ex ce pi io n. PUSQL coverts bOI h bounds 10 the values of PLS _ INTEGER data Iype.

Note that you cannot change the counter inside the body of MR loop as you are not allowed to reference courser in {he body of loop.

We now perform the addluon ofsquares of numbers from 110 n using FOR loop. See l.lsting 4.9 which illustrate, the use of FOR loop.

Listing 4.9: Using !"OR loop

93