dreamlech
Anall-inclusivebookluleach you everything about Oracle PL/SQLProgramming
1Easy, Effective,and Reliable
• Quickand Easylearningin SimpleSteps
Mostpreferredchoice worldwideforlearning OraclePL/SQlProgramming
Oracle PL/SQL
Programming
Premieri2
I
10.1.0.2.0 - Production on Fr
c) 1982, 200i», Oracle. All rights
rted to:
He Database 10g Enterprise Edition Release
Mi the Partitioning, OLAP and Data Mining opl
JpL> SET SERUEBOUTPUT ON
KQL> CREATE OR REPLACE PROCEDURE salary (eno
II2 e_sal NUMBER
,
3 BEGIN
^Copyrightby DrcamtcchPress.19-A.AnsariRoad. Daryaganj.New[>clhi-110002
Thisbookmaynotbe duplicatedinanywaywithout the express written consentofthe publisher, except in the formofbriefexcerpts or quotationsforthepurposesof review.Theinformationcontained hereinisforthe personaluseofthereaiicrandanynoibe incorporatedinany commercialprograms, otherbook*, database*,or any kindofsoftwarewithout written consentofthe publisher.Makingcopies ofthisbookotany portion forany purpose other than>ourownisa violation of copyright laws.
LimitsofLiability'disclaimerof Warranty:Theauthorand publisherhaveused their bestcllbminpreparingthis hook.Theauthormakenorepresentationor warranties with respecttotheaccuracy or completeness;ofthe contentsofthisbook, and specifically disclaimanyimplied warrantiesof merchantability orfitnessofany particularpurpose.There arcnowarrantieswhichextendbeyondthedescriptionscontainedin thisparagraph.
Nowarrantymaybe created01extendedbysales representativesor written sales material*.Theaccuracyand completenessof 'He information provided hereinandtheopinionsstaled lieieinare notguaranteed or warranted toproduce;inyparticularsresults,and the adviceandstrategiescontained hereinmaynotbesuitableforevery individual.NeitherUrcamtechPressnoi authorshallbeliable foranylossofprofit01anyothercommercial damages,including butnot limited tospecial, incidental,consequential, orotherdamages.
Trademarks: All brandnamesand productnamesusedin thisbookaretrademarks, registeredtrademarks, or tradenamesoftheirrespective holders.DreamtcchPressisnotassociatedwithanypnxluel orvendormentioned in thisbook.
ISBN: I0-81-7722-S55-2
l3-y'8-«l-77>2-H55-7 Edition: 2008
Primedat:PfinimanIndia,Patpatganj, Delhi.
UthebetrechllichgeschutzlesMaterial
CONTENT S
WhaiisPl/SOLf 2
NeedofPI/SOL 2
VersionsofPL/5QL- 4
FeaturesofPL/SQL b
PL/SQLBloclc- „ b
PLfSQL VarjablejamiConstants 7
PL/SQLConltolSltuclures 7
UsingSQLwithinPL/SQL 7
PL/SQLCollections a
PUSQLRecords 6
PL/SQLSubprograms 8
PLSQlPjcbsjgS B
ExceptionHandlinH...., , 9
New
FeaturesaddedinPbSQLforOracle tug 9PL/SQLArchitectureinOracle 10
Summary ... „ „ 1
1
DescribingBlock Structure , , , ... -.,M„,„.„.14
DiflaMlinn Sgrtinn 15
fnff ulinn aprlinn IS
Exception Section 21
KindsnfBlocfo 2j
AnonymousBlocks , 21
nlnrks 22
Nested Blocks
IntroducingDatatypes 22
NumberTypes , 22
Ntimrpr
u
Ow.n
u-iandStringUpes 24Bix>tejnTypes 27
IOBTypes 2B
Date. Time,andIntervalTypes , 29
P1;SQI 5uhtypes 32
Introducing lexical Unils 32
nplimitprs 12
Idenltfieis , , , ii
Utetala
Comments 3f»
V
UrheberrechllichgeschulzlesMaterial
Workingwith Declarations,..„ ... ... 37
LKinpUUAL'llValuo 37
Usinn
\OT
MULLCotwirjinl 37UsinuAliases
W
Avsli;iinn-niQ[H-i,»or 3tt
AnlhnuHitOpi'i.ilors - - , —.39
Lofiir,ilOjiiT.ilurv 39
in
ComparisonUpct.ilots 40_ |H
ISNULLUptfalrir ><>^ Hp 8
(im>.m.-n.iliiin(tp- fiilnt , 40LIKE Q|HT.i1nr 40
RangOpt'Mtm;BETWEEN 41
ListOperator:IN - ^ 41
Injrodwjng AHiihuic* 42
Usingllu'^.TVPF AHfihulf 42
Usinfithe'NiROWTVPEAtlnbulf 43
ImmducinKI'L/SQlExpressions
—
^ 43BooleanArithmetic Lxprcs^ions ....„ 43
Boolean('h.irjclffl.tprrssmns , _ - ~ -..44
BooleanHalf Expressions 44
DatatypesconversioninPL/SQL-... „..„ ...45
ImplicitConversion 45
Summary 4h
ASfl! Ftmrtlnn
_
mm,
in EuncSnc illIMTrAITiiniliim 51
roNr
at Eimdam !]LQWEgjmLtffig&fu—
Horn !2IMSTBF„nf i„,n
U
ITRIM.mrlKTKIMfimrliiim i!
BFPIAC~Trumliim j_
SUBSa
Eundtoa , iU
TKAMSI AllEaocto ill
Il.ilrhinrlinm S'l
IU
UAH
Function .VI111(HAHlurelinn Ml
AHO MONTHS
Function nlMONTHS
BITUiFNFuniliiin 63IAST
DAY
rum-linn 1.1
vi
UrhebenechllicliocschOlzlesMaterial
Contents
331
1
NEXl DAYEuatfML, SYSTIMISIVMPt.milion
•uni.-r<:[iinrnon.
AHSFunction.
TFII andFl
OOP
Funrlinrx EQYYCIUUiilOiuu-HOUND
runrlmn,.SORTFunction..
mnvi
i,ln ft.-.n
...J4
...J£
...J&
...Mi ...JiZ ,...£B
...J&
...J&
....zq
SIGN fuiuiun- rtinvi'isinnFun*tinns
CQNVtRIfumjiuil-.
TO NUMB
fRr.inrtiim.LOBruucliuiib_
BIlLITHAMLIuiKiiuu.
rMPryjnor.milimpty
g ob
runniotw...MiypllnnmiisFunrlinns « ..
GRTATFSTandIFASTfunrlinm
_U 32 J3
_Z!
JS
_Z5 _Z6
_ZZ
-zaSummary
.
Chapter
4 UnderstandingPL/SQC
ControlSlrucluresPpscribinRPL/SQLComrolStructures J12
UsingConditionalControl Statements JLi
IF-THENSlntPinpnt _B2
IF.THFN.FI SF^rnn».n. _fe
IF-THFN-fISFIFStatrnwn. -25
UsingCA5FStatements ...Jlfi
UsingSequentialControl Statements... JIB
GOTO
Strtlpmpnl J12NllllSt..H-mnn1
Using LoopingConstructsin pi /SQi. , „ 31
IPOP
'ii.Mrmf-nlFORI
QQE
Sl-Hom-nt ,J£
WHIIfInf)P
^f^nnl
JI5Summary Jlh
Chapter
SImplementing SQL
OperationsInPL/SQL
Workingwith
DDL
andDML
StatementsinPL/SOL -SBUsinR theCREATEstatement _2fi
Using theINSERTstatement _aa
VII
UthebeiiechlllchgesGhuLclesMaterial
Ill
-| UsingtheSELECTstatement 99'I 1
| I
Uim
theUPDATtstatement 100_
j UsingtheDLTETtslalemeni 100I-inutile[JKOPst.ili-nx-nl 101
||g ir.n,-.,,Imi,V.,.im.;i-h.i-i-;ai'IiI'l (.)! 1(11
Usingthe
COMMIT
slalemeni 102gfp
UsingIhcROLLBACKstatementKM
M Jm/f
UsinglheSAVLPQIMstatement IPS1(1
B UsingIhi-StTTRANSACTIONstatement 105• M
UsingtheLOCKTABLEstatement I(10^ lP'1
Sumnuiy 107! ! !
WorkingwilhPL/SQLCollections 110
SelectingI'USQLColleclionTypes 110
Defining CollectionTypesinPL'SQL Ill
Declaring Collection Variables 114
InjtjajtejgBCollections 115
Referencing Collections 116
Assigning CrillciHuns 117
ComparingColliTtiims 118
Using CollectionMethods 121
WorkingwilhPL/SQL Records 128
DefiningandDeclaringRecords 129
AssigningValuestoRecords 130
InsertingRecordsintotheDatabase , , 131
UfidajjngaDatabasemillRecord Values _ „ 132
Summary 133
l-">rr l—lll
IntroducingCursors ....^ „.„.„ .. „ I36
Under*t,tnihnn ImplititCursors , 136
Iiinilriliimsof jmgjtji'Ciif-prs 137
WorkingwithExplicitCursors „ ,...,.138
DetUringExplicitCursors , „ 138
0[H-nii>^ f<|)luilCursor 139
ObtainingRowsfromExplicitCursur 139
CIosihrExplicitCursor 140
CurtnrAl.tihni.-t 1AJ
LxplicitCursorAtlnhuHs. „ _ 141
impinitCqrsorAttributes 146
Cursor
FOR
loopMB
Oirsni Variahlra 150
Cursor Expressions , 155
viii
UrheberrechlllchgeschutztesMatotlat
Contents
Ml H.T
rOK
IIPDATFillfunnn
152Chapter
8 '
UnderstandingSubprograms
inPL/SQL
161 162PL/SOLProcedures 162
rux/Lrunciions , , ,.
WorkingwithSubprogramsIViMmelers
...164
167 167
)sinj;Not.ition lorSubprogramI'.ir.tmt'iL'K 168
I6B
173 174
UsinRRecursion withSubprograms.. , 175
UsiriR
AUTHID
Clause 176177 177
Chapter 9
UnderstandingPackages' inPl/SQl 179
180AdvantagesofPackages „ .. H t
IBO 182 183 The
STANDARD
PackageThe
DBMS
PIPEPackage „ TheUTLFILEPackageTheUTI.HTTPPackage The
DBMS
SQLPackageIBS IBS
186 1B6 IB7
The
DBMS
ALERT Package 189190 TheDBMS.SQLPackage
The
DBMS
PIPEPackaue190 19.)
I»
195
The UTL FILEPackage 197
The UTLHTTPPackage I9B
200
Building\tuii
own
PWrKiWIf.iln n
ii.! 203206
IX
UrheberrechllichgeschulzlesMaterial
iP
tabaseTriggersin
PI/SQL 207
DMITrmm-is DDITrfaen D.it.ikm.-Unithii:j'-r.
ISSIIMIOIIriTO'i*..
M.nnl.uningrriggefS InablinRor DisablingIrtRRits..
Droppingii >"1 m<
RenamingThimerv
M.'ntiiii.1.-Viliininniiii-Il.mv.Klinn*liMii.;I:v.'<[-
Summary
.
..206 20B
..m
..211 -212
..
JM
.216 ..217 ..217 ..218 .219 ..211
..221
UnderstandingI'lySQL Exceptions ...
Ift-BuillInceptions
..226
..226
.230
RaisingExceptionsinPL/SQL ~ .. ...
Ih..|MIVt-.Uffn.nnt
„ 231
•l'
234 2)5
UsingSQL
CODE
andSQURRM.,._ _236 238
OlthinjiUnKindlcdIvccnlinns ...~„„™^.. „239
K Wp«inPI/SQL
241
InlriHlminjOhjixlJ\\iCb 2-12
UsingObted Type 242
242 24.1
245 J4M
InheritanceInI'lsen 252
Mi'thod(tvt'inrlini^ 254
Di-nnincSQLTypos uquiwilcnttoPUSOLCollection Ivpcs ...J '
.
1siny PISOI1nllfUion*. WilliSQl(>l>|OClIvpes .'511
Summap
>!,>X
Urfiebe'rechlUchrjeschOlzles Material
Dalabase
managemenl isverycrucialandtediousworkforevery organizationasdatabases containsallimportantinformation's ofan organization.Oracleisadatabaseusedinalmost every organizaiiontormanagingdate,Oracleisaflexibledatabasethateases theproblemof managingdatastoredwithinyour system oronOracleserver.Now,
rhequestionarisesthathow Grade
manage*,[he dala.The answerfar (hisquestionisFL'SOL, whichIsused(ormanaging the database. PL/SQL is avcrv efficient andeasier lo learndatabase programminglanguage designedto manage database. Each Oracle versioncomes with itscorresponding version of PL/SQl.PL/SQl isaproceduraldatabaseprogramminglanguagethaiextendsIhi:functionality of StructuredQuery Language<5QIJandusesthemwithin itsproceduralstatements.PL/SQLusesSQL DDL
andDML
statementslo perform operations suchas [.bating, altering, deletingthe database.Theseare thebasicoperations requiredtomanagea database. PL/SQLexecutesSQL
statements withinPU5QL
bfock. whichIsihebasicunitofPIjSQL, PL/SQL isaveryflexible databaseprogramminglanguagethaisupportstheadvancedprocedural programmingconcepts andelements,suchas:Support forall
SQL
datatypesalong with its PL/SQL defined datatypes. Useof control aalenientsitF-blLSE-Tatfm,iterativestructures(KOR-LCOt,WHILE-LOOP).Supportforsubprogramssuchasproceduresandfunctions,trigger*,,cursors.
Exception handlingthatletsyoucreatebugfreeprogramandhelpsinmanagingerrorssuch asdata not found.
SQL
canissuennlyasinglestatementatatime,whichwillbecome
moretimeconsumingwhen
needtoexecutemany SQL
statementsandleadsinlowdatabaseperformance3iutPL/SQLallows youlosendmultipleSQL
^larementtodatabase simultaneouslyandthusreducestheoverhead ofaccessingthedatabaseforeverysingleSQL
sljtcmcntIn thisway,therearclotsofadvantages ofusingOralle'sPL/SQL,Inknow
[hoselet's startworkingwithPI/SQL.TostartworkingwithPL/SQL, you must needto
know
itsneed, advantages,archilecture,and features.Thisisallthatwe
coverin thischapter.What
isPL/SQL?
PL/SQL isprocedural language, which is availablewith Oracle.PL/SQL is not a standalone languagebecauseitworkswiih Oracle.Itisan extensionloihe
SQL
(Structuredquery language, adatabase languageusedloperform various functionssuchasqueryingandupdatingdata,ona database).PLinPL/SQLstandsforprocedural language.PL/SQLextendsthe funciionaliiy ofSQL
and(hencombinesi(withproceduralfunctionalitysuch asloops,procedures, cursorsloprovide hellerandmoresatisfactory resultthanSQL.Now,
rhequestionarises ihatifwe
alreadyhaveSQL
{.\flexibleandeasytousequery language) thenwhatistheneedto extend thefunctionalityofSQL
by PL'SQL^Vou musttiecuriejus toknow
(hatwhy we
need PL/SQLand whatare thereasonsbehindittsuccessandinmakingita ubiquitousdatabaseprogramminglanguage.Now,we
willdepkttheneedIndevelopPL/SQL.NeedofPVSUL
As
we know SQL
isa very easyandmoreconvcnienl dalabasequery language but besidesthatithas
some
limitationsthaibecome
theneedlordeveloping PL/SQL.InSQL,we
havetoexecute a singlestatementaiatimerSo,ifwe
needtoexecute multiple statements then Oracle database 2Chapter1:Introductionlo
PUSQL
must becalled several limesTo execute all ihe issued statements thaireduce ihe database performance.To
improveIhedatabase performance,PL/SQLisdeveloped.Therewas
aproblem with (hesecurity ofdatabase as thecodeisexecutedonclient-sideratherlhanserver.We
were notablelohandle exceptionslhalleadinsuddentermination ofprogramatmnlime.To overcomealltheseproblems,FL/5QLhasbeendeveloped.PL/SQLhaslotsofadvantagesthai have
made
itaverysuccessfulandomnipresent daiahaseprogramminglanguagethaiisinwide usewith Oracle,Herearegiven theadvantages of PL/SQL:Easilyadaptableand
SQL
supporting Enhanced PerformancePortability
Security
We
will studyall theseadvantage* ofPL/SQL in the sequence. Let'sstart studyingall these advantagesin detail.Easilyadaptableand
SQL
supportingPL/SQLsupports theentire characteristicandstatements availablein
SQL
such asselect,insert, update, delete. Databasecan easily liecreated and manipulated by incorporating theSQL
statementsinPL/SQLblock.PL/SQLsupportsall datatypesthataresupportedby
SQL
soyou do nothavetoconvertSQL
datatypesinPL/SQLdatatypes.PL/SQLafsoallowsyoulouseSQL
operators, functions,andso on.PL/SQLiseasytolearnandunderstand asmostof thecharac[eristicsareextendedfrom
SQL
and the synta*usedin PL/SQLisverysimpleTo learn asituseslotsofkeywordsthaiclearlyexpress thepurposeofyourcode.BeingfamiliarwilhanyoftheprogrammingLanguage suchasc,c+-*-makesiteasier tomemorize anduse thePL/SQLprogrammingsyntax.
Enhanced
PerformancePL/SQLprovidesbetterperformancethan
SQL
becauseoneSQL
statementcanbeprocessedata timebydatabase,which meansifyou haveloexecutemorethanoneSQL
statement thanyou haveloaccess databaseasmuch
asSQL
statementyou needloexecute.Accessing the database severaltimesresullsinthecongestioninnetworkasdatabase are generallystoredonserverand thus ihe time toprocessSQL
slatemenl will automatically increased, which leads in low performance.In
PUSQL,
morelhanoneSQL
statementcantiesent toOracle databaseforprocessingbecausein PL/SQL,you cancollectallthestatementsin PL/SQLblockwhich isthe basicstructureof PL/SQL andalltheprogramsinPL/SQLcan noibecreatedwithout
PUSQL
block oryoucanalso usePL/SQL subprogramslocollectmultipleSQL
statements.A
subprogramisaPL/SQLblock thaiconsislsthesequenceofstatementloperformiomp
specifictask.A
subpn>gramtanbe calledbyotherPL/SQLprograms. Thus,Oracle databasewillbe accessed onlyonce andthere willbenocongestioninnetwork,whichresultsinthebetterperformance. See theFig.PU5QL- Lllounderstand theworkingwithout usingPUSQL
andwith usingPL/SQL.3
IndependentSQLStatefnenL
BEGIN THEN SQLSlalernenl ELSE
SQLEJaleinent
ENDIF:
END,
OretlaDatabase
PUSGLblackrtnlhmultipleSOL$t£lsnttfil5 Fig.PiySQL-1.1
In Fig.PI/5QLl 1, ii is clearly rfepiried lhal before theuse ofPL/SQL. an application hasto communicatewith thedalabase withseveralindependent
SQL
statementsthaiultimatelyleads inoverheadonthedatabaseandreducesitsperformance,while with the use of PL/SQL,youare passingseveralSQL
statementswithinsinglePL/SQLblockstodalabaseatsan>etimeandwhichSQL
statements hastoheexecuteddepends onthe conditions provided within PL/SQI.block.In thisway,PL/SQLinOracle providesbelterperformance.Portability
PL/SQLisaportablelanguage,thatis,programscreatedinIheOracleenvironmentcanalsobe executedonany operating systemthat supportsOracle. PL/SQL programsfollowsWriteonce andruneverywhere(withinOracle environment) slogan.
Security
PL'SQLprovides highersecuritythan SQL. PL/SQL slored procedures places the application codeceniiaUyonserver ratherthan platingunclientsyslem.Byplacingtheapplicationcode centrally,you can hideIhecodefrom otherusers.You cansetthepermissiontoaccessPL/SQL procedure by varioususers torperformingdifferent activitiessuchas updating, deleting atableor data within a
ublc
These arc some advantages of PL/SQL due which PL/SQL is a ubiquhous daiabase programminglanguage. Let'shavean overview ofthe various PL/SQL versions to
know
the enhancementmade
inPL/SQLversions released with everynew
Oracleversion.Versions ofPL/SQL
Tilltoday various versions ofPL/SQLhasbeenreleasedalong wilhtheversionsolOracle.Every
new
versionn|Oratletomeswilhitsown
versionolPL/SQL andeverynew
versioncomeswith additional characleri^ttL?from previous versiontoprovideyoubelter iunction.ilitv.In thisiwiok,we
areconsideringIheOracle1Og andthePL/SQLversionthatis10.0thathasbeenreleased wilhit. fable1.1cfepiclsallthe versions availableMiltherelease ofOraclefOg.4
Now, we
have discussed thathow
Oracle's PL/SQL hasbeen improving loprovide better performance.lei'sstudythe features01PL/SQLlu
know
dllthdlPI/SQl tonsilsandhow
ithelp-*inmaking databaseprogrammingeasyandffficieni- Here,we
studythesefeaiures in hrielbecauseall features will bediscussed in detail furtherin this book.We
alsodiscuss thenew
features includedin(hePL/SQLforOraclelOg,Features of PI/SQL
Many
ofthekeyfailuresinOracle1Ug PL/SQLaresameasiheprevious versions{PL/SQL9.2).StillIhisversionhas
some new
improvements duetowhichthe databaseperformanceismoreenhanced,PL/SQLhaschangedthe
way
ofdatabaseprogramming andbecomes[heomnipresent databaseprogramminglanguage.PL/SQLallows using
SQL
statements withinPL/SQLblock.Programflow can be controlledand multipleSQL
statements can be sent to database at The same time. PL/SQL subprograms (priHnedure&andfunuiorvi]canbeusedtomake
theprogrameasier.We
willdiscussallfeaturesindetailsinforthcomingchapters,buiherewe
canhaveanoverview ofallthemainfeaturesofPL/SQLalong with thenew
featuresaddedin(hisversion ofPUSQL
in Oracle1Og.Herewe
discussihefollowingmainfeatures,whicharethenfollowedbyihenew
featuresaddedin(hisversion;
PL/SQLBlock
PL/SQLVariablesandconstants
u PUSQL
control structures UsingSQL
withinPL/SQL PL/SQLcollectfons PL/SQLRecordsU
PL/SQL SubprogramsPUSQL
packages ExceptionHandlingt1erer
ue
startdiscussingallthesefeaturesPI/SQL Block
A PUSQL
pn>gramconsistsminimum
nne PL/SQLolock. flisnotpossibletocreateaPUSQL
program withtmlPUSQL
blockthat'swhy PUSQL
block isvery importantand Ittisicunit of PL/SQL.A PUSQL
block hasdifterentpartsandthatpartsareDeclarativepartwhere youdeclare itemssuchas types, variables;itisoptionalpart,ExecutedpariwhereyouwriteproceduralandSQL
statementsandisnecessarypari ofPL/SQLblock;withoutitPUSQL
block jsincomplete, andfinalpartisExceptionhandlingwhere youprovide(hecodetohandle exceptions;itisalso anoptionalpart.A
PL/SQL block has tour ke>words, declare, begin,exception,
and end.declare
keywordisusedtobreak thePL/SQL blockin declarativepart, BilGIN isusedtodefine(he Executionpart,EXCEPTION
keywordisusedtostarttheexception handling,andEND
keyword 6I;IntroductionlaPL/SQL
isused toendThePL/SQLblock.See the following snippet tounderstand (hePL/SQL block structure:
Variables
and Constants
PL/SQL allows declaringvariablesandconstants so that Ihey canlieused in executionpart.
Variablesandconstantsmust haveTobedeclared belore usinginstatements (Executionpart).
Variablesand constantscan have any
SQL
Isuch asNUMBER, CHAR,VARCHAR2)
orPL/SQL datatype(BOOLEAN).Theonly differencebetweenthe declarationofvariablesandconstantsis thatwhile declaring constants, you need to useconstant
keyword and valueshould be assignedatthetime ofdeclaration.Incase ofvariables,valuescanbeassignedinexecutionpart.Control Structures
It isavery importantfeature ofPL/SQLthatletsyouallowaddingconstraintsonstatementsto send multiple statements to database at the same time rather than sending the several independent statements as
we
everdidinSQL. PL^SQlprovides the following controlstructures:Conditional controls: This control allows you to execute several statements based on different conditions.
You
can check those conditionswith the help ofIF-THEN—ELSE
statement to execute the proper statement. IP clause checks the condition and if the conditionistruethen the statementwrittenunderTHEN
clausewillbeexecuted otherwise thecontrol transfers toELSE
clauseandthat willexecute.Inthisway,conditional control structureworks.Iterativecontrols:Sometimes you needtoexecute asequenceofstatements multiplelimes, whichwasnot possiblewith
SQL
butPL/SQLprovidesyouiterativecontrolstocomplete yourrequirement. PL/5QLprovidesyouseveral loopssuchasloop — end
loop,for
loop,while
loop.Alltheseiterative structureswillbeexplainedinChanter-4.Q
Sequential control: This control allowsyouto transferthe controlfromonepariofprogram toanother.PL/SQLusesGOTO
keywordtosupport sequentialcontrol.within
PI/SQL
hasextended all thefeatures ofSQL. II allows using all
5QL
dataypes, operators, andsoon. UsingPL/SQL, all theDDL
andDML
statementscan beexecuted from withinPL/SQLblock.7
PI/SQL
CollectionsIike-miner pingrarnminj;language-,such asi,i+ PL/SQLalsoallows urn
m
groupelementol similard,Va1vpevfni.i+-. jjmupr>iHi'meritsnisamel J Hil
H"i (
p*"-
iscInnt'^ilh Ihelis*.'orarrays, lushtable (3 1sd s-o an. hut here arrays ,irc tailed,is varrays and hash table Lire
known
as absntlative.uravs.It> tjliarefamiliarwithanvoilierprogramminglanp,Lia£esuchasc,c+-thenit,lining i
Jl/SQI. toilerlirms heroine vitv easy but it vr>u an' no| fari«lia: wilh any other programmingI.i
n^.'ij,Lyf-"andit i
1-llie: ar-sI languageurn are siudying(ht'ii
akn
have no needti>worrybecause PL/SQL isone,i^ languagelounderstand TheList.101PL'SQLcollectionswillhe depictedintheChaptcr-uor Jlnsbook.
«/Sfl£ Records
keloids are likt? data stiuctures used in programming languages such as r. r+-. As data strutInn'sareusi'dtogroupprionselernerilsofrliiiereiitd,iiatypes,in|iitjsanie
wav
reinrcJ-.areLisi'ii."Ilie 'ink diltereiirv between(olleiboils and records is lb,il ie^.11 rnllerlionsvon i.m gioup clemcnlot similardalalypeandnsinjirf.-r.ordsdisstmiLir datalypestanIk1grouped Fur
r\ampk\
u>nu vv,inl tntoiletr (hi1 informationrir an empluyee such as his/her name, age, a<ldres> (henyou<_andothis\y,using asinglerecord hutrfyouusocollectionthenson havelo nirikt'\annusrnllnlion'suthash.,irc.iy)ingroupllu."elementsolsimilardalavpe. Theuse<APL;
SQL
retorriswillhedeprrledin tin-Cha pier-ftoJthhbookPL/SQL Subprograms
f'J
SQL
also.illuu'iiti-nin^pioieduresaridiLirictitirisasoilierprogramminglanguages.Inl'l_/S"QL, procedures and tunctions arccollectivelyknown
jssubprograms.A
f'l.'SQL subprogram is innii.irin!'l'SCJI hlrnk ,ir:ori'.minishlni.k'.cMCjilih,LT,\siih[iin^r,ir[irnn^[Ih^'i'snnu'name
solha(ilianI>ilinuiko!.mvufirrr-inihrprogramorinanyiHlu-iapplkalion
.Subprruirani!.arc \\-t\ inipurjjni in l.ir^c applicnion,ns it breaks
down
the bi£ andcomplex apphta'ionIndi oa>ilvni.iii.inealilcmod
u let.SuhpruijMnjshaveprornotetJiher.oncr.'pfnireLisabihty. fhesame subprogramcanIn1usud nioie thanonetimein \arj<jlikapplnadons
Once
teitccisuctesiiullyIheniltan\n.-uscrldirer tlym
.niv.i;)(>1kalumi\ilhi>nl\v,Lstiriji
i
timenn.vnliiij;il.ii^mi,iridai^amIncar\i-\\applurition, E'L'iQLproteduresandHmctions aresliticlurjlksamebuthavennl>oneditferent.t'inwhir ha ujiiLlianhas.-^"'J.-;.tlaii^e.Subprogram-,\\NIespl.irnindetailinChapM-r-Jiit\\ht\bnr>k.
Pi/SQL Packages A
PI SC par kajifi>knouria1-fkitaSidsenlijct!,
w
hir hi*-um'iJInbundleloj;ir.,iilvrelaledPL'SQLpji>iI'duri"'
mm
lions VI.'^QL iinrJc^ with In)', ril [iri'dETirierJ p.n ka^e*. surb as::- L
:.
v
t7f, '..p,yy _;i;t r:
-
thai ran he
n^d
rlirettbm
ynurapfilit.stinn orn™
fi,uka^es%\ilri^nor riwn^peritiratmu^-ivhithran,itsobei re.iti'rl,
A
I'i/SQI patkfik^eba^Hsup.iils,•yp-\ilii-Hirmandhmk
S\'i-<iln.ilirjrip.irti,inbi'(iimIf-iJwilh In" o-e ol "i:v.1. yr- - slafemenl and use lo deiiaie con^iants. variables, procedures,Uini'tions.cursorsandexcqulionsinapackage.S
1;in!mdwHonto
PackagebodyIscreatedwith theuseof
CREATE PACKAGE
BODY,SQL
statementand package bodycontainsproceduralandSQL
statementBasicsirue lure tocreatePL/SQL packageisgivenThisisjustanoverviewofpackagesinPL/SQL.PackageswillbeexplainedindetailinChapter-9 ofthisbook.
Exceptionsareruntimeerrors thatinterrupttheexecution ofPL/SQLprogram.There are
many
such asprogramisnotproperty designed, dividinganynumberby zeroforoccurrence ofanexception.Toavoid theprogram interruption,PL/SQLprovides themechanismtohandle the exception.Tohandle exceptions, enclose theprogram codewithinbegin
andend
clause with exception handler In PL/SQLblock,exception
keyword isusedtostarttheexception handlinginPL/SQLblock.PL/SQLalsoallows youtocreateyour
own
exceptions along wilh handling [he predefined exceptions(thrstype ofexception generally occurwhen
any numberh
triedtobedividedby zero,stackoverflowandsoon),zero divide
exceptionwitloccurwhen
youtrytodivideany numberbyzero.Tocreateyour
own
exceptions,RAISE
statementneedstobe used.How
tohandle exceptions andhow
togenerateyourown
exceptionwillbeexplainedm
Chaptei-11ofthisbook.Withtheendofpreceding givenfeature,you mustunderstandthat
why
PL/SQLisso popular,now we
continue with thenew
featuresaddedinPL/SQLforOracle10grFeatures added
inPI/SQL
forOracle lOg
featuresaddedin thisversion ofPL/SQL have
made
itmoreconvenient,easier,andmore automaticto use.New
featuresaddedin thisversion are asfollows:Q
ImprovedPerformance:Thisversion of L'L/SQLcarrieswilhmore automatedfeaturessuch as reuse the expression code, introduction ofnew
datatypes for processing scientific operationswhichhas involvedinimprovingitsperformance,Support for
FORALL
statement:PDRALL
statement lets you allow to processDML
statementsmoreefficientlybyiteratingover non-consecutive indexes,PL/5QLhas
indices OF
andVALUE OF
clauseslo iterateover non-consecutiveindexes,forall
statementuses specifiedindexinacollection to ilerateandprocess thestatements.9
Introducing
BINARY, FLOAT
andBlNARY_DOUBLF
floatingpointdatatypes: These are twonew
introductionsm
thedaIatypes.These datatypes supportIEEE 75-1 loniialandareof floating point type. These are used for intensive scientific compulation where floating dalalypes areusedinealculalion.EnhancedOverloading:Overloading hasimproved in thisversion.Subprogramslhathave differentnumericdatatype*asparametercan be overloadedinthisversion.
Improved NestedTables:No*v vou have more enhancedNestedTallies.Usingthisversion, nestedtablescan becomparedlorequalitysuchasvon can checkthatwhethera nested tableisasuhsel ofanother nesledlable or nut.youcancheek wheihtraparticularelement
isa
member
ofaspecificnestedlableornot.CompileTimewarnings:Thesefeatureshelps
m
making.1PL/SQLprogrammors-robustand well functioning;. By using ihis feature, Oracleissues warnings during PL/SQL program compilationwhen
foundany problem suchaspassingchar valueto lloatcolumninINSERT
statement. Youcan use L-LsOL VJ/ilJN'[NGi initialization parameterand DPV3WARNING
pankagetomanagesompile time warnings.
Implicitconversionbetween
CLOB
andNCIOB:
Keiore introductionofthisfeature, user ha\etouse':'j_i:LOaand7_iN^LOh
toconvertCL-'iintoacLOb
andnclob
intoclob
but
now
userdonol have(oconvertthemexplicitlybecauseinthisversion,Oraclemakes implicilconversionbetween them whereverrequired,U
FlashbackQueryFunctions: Tinsfeatureisusedtoknow
thetimeslampasviiMled with a particular^CN
(SystemChangeNiirnljefiandalso 5"tJnitpartiiularmoment
oftimeandfor tinspurpi>seryou have ^£t:_r"JTT^I^'TAi-'P;mdTIV:TfjTA^!F_TCj_C!."-Nfunctionsto use..jch
TO 'llM^TAUr
Junction takes^cn
numberasparameterandreturnsthetimestamp assnt lated with tli.itSCX
while 7rM^T.-MP
TO .S'li function takes time value as parameterandreturnsilie3i7Natthatriionient.Here,
we
have completed discussionon PL'SQL featuresaod thenew
fediu resadded inthe PIjSQLforOraclel()g.Let's study the basic working structure oi PL/SQL in Oracle.
We
are talking about the architecture ofPI-/SQLinOracle,ftisnecessarytounderstandthearchitecturebecauseifyoudo notknow
thathow
Pl.'SQl proc essiheslaiementsirnludedinPI/SQlbkick.itbecomesdifficult tounderstandIho PL/SQL programming.PL/SQL Architecture
inOracle
Aj chile* lureorPI.'SQL representsitsbasi<workingintoordmatiouwith Oiacle.
A
PL/SQLblock orsubprogramtonsils, ofboth procedural statementsand SQI statement Pi.'SQI.architecture describestheprocessthathow
PL/SQLinoracleinterpretsaPL/SQLblock orsubprograms.PL/SOLarchitectureinOraclelOgtonsists otPL/SQLblock orsubprogram, PL/SQLengine,and Oracleserver.PL/SQL engine compilesandexecutesthePLMJI.block orsubprogram. Oracle databaseorapplicationdevelopmenttoolssuchasOracleforms.OraclereportscontainsPL/SQL eiigme, PI/SQLengine contains PL'5Ql proceduralslatemenl executor toexecute procedural statements within a PL/SQL block orsubprogramand Oracleserver contains
SQL
statement executortoexecutebQl
statements.I'j;.SQ| engineandOracleserverworkinco-ordinationto processa PL/SQL block or subprogram. Fig.PIASQL-l.2 depictsthatbow
PL/SQL engineand Oracleserverworktogetherandprocess aPL/SQLblockorsubprogram10
Chapter1:Intmluelkmto
PUSQL
BEGIU
IF..THEN SOLSlslemenl ELSE
SQLSldFnenl ENDIF:
END:
Procedural Slslemenls
SQLStatements
Procedural SlaFEirsnl Exocutor
PUSQLBin*
f
\Oracle Server
SQLStelamenl Esecutor
V
)Fig.rUSQL-13
PL/SQLengine accepts procedural statementsand
SQL
statementsas input.PUSQL
engine then process a! procedural statementsthrough procedural statementexecutor and send theSQL
statementstoOracle databaseserver toprocess. In thisway,a PL/SQLblock orsubprogramisprocessed.
Withthis,
we
have completeddiscussiononPUSQL
Archilectureandtheway
aPUSQL
hlock or subprogramprocessed.Withtheendof discussionon
PUSQL
architecture,we
finishthischapter.Bynow, vou must haveenoughideaaboutPL/SQLsuch as the requirement ofPlJSQL anditsarchitecture.Before closingIhischapter,let'shaveagfanceonsummary.Summary
In thischapter,
wc
havestudied about:TheintroductionolPL/SQL The
Need
andadvantagesofPUSQL
Thevarious versionsofPL/SQL Features ofthePL/SQL ThePUSQL
Architecture11
In
Iheworldoi {nmpultwalkm,
wLumi ivctalk,iL)ootprogramsihenwe
mustalsu take into considerationconcept.:.u<-hastheprogramslructurcanddatatype.A
programnwv
contain venous variable- to store data and those variables must be assigned with some specific datalvpes Thus, dalatvpescanl?edefinedasa formattostore daia.PL/SQL provides various dataivpes,such as ii-jif^er, f-.gjvi lhal ht'ljjCrack:iochoose aslurageformaltorinlernal representIion of objects*»nclimposear.in.^1?orvaluesuponthon*objetts,A
PI/SQLdeveloper should hoveknowledgeofllii.1 predefinedd,jl,ir>pe^ associatedwith PL/SQL solhaionecan chooseappropriatedatatypefora variableusedinanapplication, horexample,you can choose PL/SQL data typo v"A!JfJHAjJ2 forname
of<ihuman
being, Further knowledge oi theLmic programstruUurent PI'SQ! alsohelps usinpartitioning Ihe appliiotion into easilymanageahle sections.Thispartitioning alsohelps ustocatchandij\flawsm
ditfarentpadsoflhe program.We
begin ihischapter with a discussionon the PL;SQL
blockstructure movingontofurther concepts, such asdalatvpi'S. lexical units, jnHoperators whoseprior knowledge is essential lieforebeginning withPl./SQI.
Describing Block Structure
PL/SQLisalso
known
asablock-slrucluredlanguageasasimplePL'SQL programcontainsmany
logicalblockswhore eachblock solves apartoitheproblem. For example, aPL'SQL program
mav
usearlv funr [ioninside iKelftojierforrnsomeoperalionamiihis lunt'EioriIhen h^tps in solvingsome
part ofthe*problem,whidiistoheaddressedbythes<iniePl/SQI program.Toundersland the functioningofaPL/SQL program,
we
divideilsstudyintoblocksandstudy eachblocksep^iralely F.veryprogramLonsisls ofoneormoreblinks,wheree.iihblock contains relaleddoclaralionsandstalenienls.A
PI /,SQI blorkran<on^isloiIhefollowing sertionsinIhis sequence:BlockHeader Declaration
Sen
ion F\otulionSc* tion Exceplion SectionBlock Header
Theblockheader section contains(he
name
ofthebfock.IIisoptionalandused onlywhen
thereisnneedtoassignany
name
loaPI/SQL program.Name
assignedtoaPL'SQLprogramhelpsin calling it in oilierPL/SQL programs. The PL/SQL block header in PL'SQL bfockslructurc isshown
inFig.PL/SQL-2,1.
! n
i
*""'";"' '"
I evfptil.-^
|
I.M1
hp.t'lVSfjL-2.1
14
Chapter2:
PUSQL
Essentials Aftertheblock header,we
needtodeclarePL/SQLvariables(which arefurtherusedinaPL/SQL executionsection)inthe declarationsection.Declaration Section
We now
needto putinformationinaprogramblock about thevariablesusedintheblock,such asassociatingdatatypeswithvariables, initializing variables.This objectiveisachieved using the declarationsection.However,thissectionisnotcompulsory.Itisusedinablock onlywhen we
needtodeclarevariables.Ifasituation ariseswherewe
donotneedvariables, thissectioncan beavoided.Thedeclaration section starts with the
declare
keyword. After thedeclare
keyword, declarations ofvariablesareprovided.Thesyntaxforwritingthisblockisasfollows:
DECLARE
VariablenaaecspacoDatatype:
Theexecution section follows the declarationsection.
Execution Section
Execution section follows the declaration sectionintheconventionalprogramblock.Execution sectionisthemost important sectionofthePL/SQLblockstructure asitisresponsiblelorthe actualexecution of the code. Inotherwords,
we
can saythati! isIhe functionalpartof the PL/SQLblock.This sectionstartswith the
begin
keywordand endswiththeend
keyword.Betweenbegin
andEND
keywords,we
writeThesetofinstructions orcodethatwe
wan!lo execute using PL/SQL.Itishowevernot necessarythatthecode
we
writein thissectionmust produce anaction.The codegetscompiled even ifthe instructionsgiven in the executionsection donotsignifyan action.All
DML
(DataManipulationLanguage)andDDL
(DataDefinitionLanguage)commands may
be used inthissection. Listing2.1 contains an exampleof the execution section of thePL/SQL block.Listing2.1:ExampleofP1VSQLblock containingexecution section
Listing3.1 showsthecodeto retrievethesystem dateintoa variable
1v_date_time)
oftype DATE.Toretrievethedate,
we
useSySdate
(In-BuiltPL/SQLfunction).15
To display the oulpul, v.c use
?UT_LINE
procedure otHBMoj^TrnT
fln-Huill f'USQL package).Todisplaytheresult,
we
useset serverout
put on becausebvdelauliSQL
"Plusdoesnoi re.nlwhalaPL/SQL programhaswriitenwiihdbxs_outfu~
p.irkage.Wi
idiscussmoreaboul Theseconceptsfurtherinthebook.Listing2.1can be executedinthefollowingtwoways:
Using
SQLTlus
UsingiSQL"PIlisLei'sexplaineachw*tyindetail U>executeasimplePL/SQLprogram.
Using SQL'Plus
Itisusedloexecute(hePL/SQL programs andsiaiementsonasingleusermode,thaiisOracle
PV5QL
installedonasystem cannotbesharedbymultipleusers.lei'ssee
how
toexecute LislingAl
inSQL
Plus.Toexecute Ihelisting,Killow theslepsgiven here:1. Click slarl-^All Programs-*
Ofade-QraDblQg_homel-^
ApplicationDevelopment SQL
Plus,as
shown
inrig.PL'SQL-2.2.16
fiSrFI^QLZr7 TheLog
On window
appears,asshown
inFip.PL/SQL-2.J.2: [-ivi/tittls
2. In the.Log
On
window,enter theuser asscoltintheUserName
textbox,asshown
in3.
Now,
enter Ihepasswordas ligerin Passwordlextbox|FigtPI7SQL-23).4. Then, enter Ihe hoslsiringintheHost textbox,,is
shown
inFig,PL/SQL-2. 3.5.
Now,
clickTheOK
button -2,3}.TheGrade SQL
*Plut-window
appears, <isshown
in Fig.PL/SQL-2,4.G.
Now,
write ihecodeshown in Fig.PL/SQL-2.4.2.1 in theOracle
5QL
'Pluswindow,asshownin:UtiliseIt.lJ.?.!- anlur J*n39IV2I:1f?«B CO191?,it**. (Illright*-Ibr^m.
hePirlitiaalnij,m.flPjrd UliEHUEHDIIFlJIII
H
KCLME
J i>_ddle_ll"*IHIE;
3 HGIH
t ULEtr IMID
7, Now,press the
ENTER
keyto thecode.As soonasyoupress iheENTER
key, ihe outputwillbedisplayedasshown
in PL/SQL-2..K17
Thisis(lieprocesstoexetule thePL/SQL programs andst.ilemcnlsin
5QL
"Plus.Using iSQL'PlusConsole
It
h
ustdtoexecutethe PL/5Q!.prngums
and SQL statements(>rinelwork'd SystemsMultiply usersinihesome network can access OraclePL/SQL installed onasystem bvspecifyingthe networkpathiForexample, tip; .'/1otJ-rest
:r-S60.i.^qlp_U5.')-Ifl's fnllow Iheitepsgivenhereloexeiult?Lislitig2.1 iniSQl.'Plustonsok1:
1. fnrerthe
UKL
'lorexample, o—
p: '.'IcejlncG^
:b5&J /laqin.-js>m
IheAddressbarof yourweh
browser fFig.PL^QL-2-f^ to open the Oracle i$QL*Plus login consoler digPI/SQI-2.7ji
riS-PUSQl-T-b
Click the
Go
button, as shown in Fig.PL/iQL-2.f). The iSQL'Pluslogin console appears ilifl.PlySQL-2.7).In(he iSQl.'I'Lus login ton^okvenk'fiheu^er
name
iCOUintht*Usprnamelext iiekl,as showninFig.PL/SQL-2. 7.Then,enler thepasswordinthePasswordteMlieldfFig.PL/SQL-2.7^ Inourcase,
we
have used thederailIipassword(hatislifter.Enter the host string (hatisorrlin
Conned
Idenlifirrtextlidd,asshown
inFig.PL/SQL-2.7.Vow,
dick the Login button(Fi[i.PL'bQL-2.7i. The Oracle iSQL'Pltisworkspacewindow
appears, asshown
inFig.PL/SlJL-2,H.1B
Clmpler1:PL/SQLEssentials
Ltgin
Fig.PUSQL-17
7, Write thecodewritteninListing2.1 intheworkspace
window
,mdpresstheExecute bution, asshown
inFig.PL/5QL-2.8.The Oracle iSQL"Plusworkspace appears onceagain to display the output, as shown in Fig-PtVSQL-2.9.
19
' - '
Fig.PUSQL-2.9
Thisistheprocesstoexecule thePL/SQL programsusingiSQL'Plus console.
Now,
ifyou want toexecutesome
more programsthenclicktheClear button, asshown
inFig.PIVSQL-2.10.Thiswillcleartheworkspace
window
(Fig.PI75Ql-2.10)andthenyou cancontinueworking with otherPUSQL
programs.|Boo1UUJI
Won
I(VFi^PL/SQL-2.10
20
UrheberrechtlichgeschutzlesMaterial
2: Essential*
So, thesearc thetwo processes toexecute the PL/SQL programs.
No«,
Id'scontinue our discussion with the nextPL/5QLbloc kstructure thatisexceptionsection.Section
Exceptions arc certain abnormal conditions, which occursometimesduring execution of a PL/SQL program and causeiheprogram(oterminate.Exceptionsectionof theprogramblockis
anoptional one. Allsections oftheprogramblock except the execution section are optional sections.To
make
aPL7SQL programtreefrom runtimeerrorsor exceptions,youarcsuggestedto use exception sectioninPUSQL
programs.Theexception section in a block begins with the keyword
EXCEPTtON
and endswith (he keyword END.This sectionbasicallycatches theerrors thatoccur
when
theprogramisexecuted.Thesectrors arecaughl using the various function?providedspecificallyfor thispurpose.Some
functionsfor exception handling are provided under theSTANDARD
or DBMSSTANDARD
packages.We
readmore onexceptionsinChapter1[(Handling ExceptionsinPL/SQL).
Thefollowingcodesnippetshowsasimple
EXCEPTION
sectionorPL/SQLprogram.Afterunderstanding the blockstructureofPL/SQLprogram,let'sstudy various[ypesof blocks.
of Blocks
Depending ontheheadersection,there aretwo maincategoriesofblocks—
anonymous
blocks andnamed
blocks.A
third kind ofblockknown
asnestedblock is alsoavailablethatcan containoneormoreanonymous/namedblocks.Let'snow
studyalltheseblocksindetail.Blacks
Anonymous
blocks,as thename
suggests,arethose blocksthatdonothaveaname.Therefore,we
dono(haveanyblockheaderfortheseblocks;hut iheyhaveoneorminesections,which aredec bra!ion,execution,andexception.Since theydonothavcjdrnuiici, cannotcolltliem.Due
tothis,anonymous
blocksare alsonotstored in thedatabase However,ananonymous
blockcancallothernamed
blocks.Usesof
anonymous
blocksinPL/SQLare:Declaringvariables ihatcan be usedintheexecutionsection.
Declaring cursorsthat canbe used intheexecutionsection.Cursors arcusedto access element* stored in a collection.
We
will study in detail about cursors in Chapter 7(Understanding CursorsinPL/SQL).21
Executing Cursor
SELECT
^i^(friirjn[rNamed Blocks
N^meH
blocks aretheblot ks thathavesome
name.Itisobviousihat11a blockisanamed
block,irwouldcontain.1blockheaderbecause[he
name
ofiheblock isdefinedinablock header.Therefore,anv
named
blockwouldcom
j in atleasttwo01mnreblocksections.Thisijibecausefile fx?iuMon section is a ncie^sary section torany PLVSQI block and if
we make
header compulsoryIhcntherewouldlieIwo
compulsorysectionsin ihi-hloik.Overall,named
blockcm
hujve.illtheloursections— block header,declaration,execution,andexception.Nested Blocks
Nested blocksare yetanother important kindot PL'SCJL blocks.
When we
haveblocks placed insideotherblocks,we
call thisphenomenon
asnestingandsuch blocksareknown
asnested blocks.Thesenes'tedblocks mightfurtherdifferfromeachotherdependingonseveral different<riierions.
One
ofnuth impoitanl cnterions isMielevelofnesting. Each Nested block has a certaindepth. Thisdepth isthe numberol levels to whiih ihat hloiklirfs been nested, for example,rfwe
h.ive.iblock wilhrnablock,thenitiss^id tobe nestedto leveloncrJltheblock containedinsideIhe blockfurtherContainsanotherblock,thenthe levelof nesting increasesto two.Nestingisallowed onlvintwosetlions—
exetutionande\<eplmn—
<iithePL/SQLblock.Lei's
now
discustheprionsdata types availableinPL/SQLtostorerealworldentities,suchas numbers,texr.andimages.Introducing Datatypes
Havingknowledgeabout datalypcs
n
essentialbe'orebeginning with applicationdevelopmentin any programming language because datatypes form ihe most haiic building blocks for developingany program.
PLAQl
supportsall thepredefined datatypesinSQL andalsosome
additional ones. There has to be a datatype for even1 variable or p.irameter in PI/SQL.Depending oniheneedojtheapplication,
we
canchoosethedatatypethatsuitsus thebest.Venouscliil0typesavailableir>PI/SQlare:
J Number
TypesJ
CharacterandSlungIvpesJ
NationalCharacterT\pesliiif)k-rinTvpe1
J LOU
TypesDaleand TimeTypes Subtypes
Number Types
Number
typesare sralardatatypes.Thedatatypesthai holdsinglevalue areknown
as scalar datatypes.A*thename
suggests,numbertvpes areused\usiorenirmerii v.ihtes.These numeric vafuesmay
includeintegers,real numbers. UsujIIv.we
usenumbertvpeslor fieldsthatneed numbersasvalues,suchasagermeasurement22
Chapter2:PlJSQLEaraiMls The
number
types arefurtherdividedintofollowingtypes:BINARY.INTEGER NUMBER PLSJNTECER BINARY.DOUBLE BINARY_FLOAT BINARYJNTEGER
BINARy_INTEGER
storesthesignedintegerin a two'scomplimentform.Therange of binary typesisfrom-2147483647
to+21474Q3647. This type isgenerally usedwhen
iveneed lo perform arithmeticoperations.Ithas followingsubtypos:NATURAL: May
store integersinrangefrom0lo214748i647.POSITIVE:
May
store inlegcrsinrangefrom1lo2147483647.NATURALN: Same
asNATURAL,bulcannotassign null to integer variables.POSITIVEN:
Same
asPOSITIVE,bulcannotassign nulltointeger variables,5ICNTYPE:ItisusedinprogrammingJri-statelogic thatisanintegervariablecanonlyhave valueeither-1, 0,or1.
NUMBER
The
NUMBER
typecanholdfloating-poinivalues orintegersintherange[Venn1.0*1 0A-130to 9.99x1
0
A125,Thegeneral syntax of
NUMBER
typeisasfollows:NUMBERC(P reelsion.seal e)
]
Intheprecedingsyntax:
precision:representsthetotalnumberofdigitsthatanumbervariablecarstore.
scale:representsthetotalnumberofdigitsthata
number
variablecan containtotherightof (hedecimal.Thescalecanrange from -84lo 127.We
can only useintegerliteralsfor specifying precisionandscale.Now,
see ihesubtypesofthenumber
typo.DEC,DECIV-AL,andNUMERIC: Usedtodeclarefixed-pointnumberswith precisionuptoJB decimaldigits,
DOUBLE PRECISION
and FLOAT;Usedlodeclarefloating-pointnumberswith precision uplo3tidecimaldigits.PEAL:Usedlodeclareflonltng-poinlnumberswith precisionuplo10decimaldigits,
INTEGER, INT and
SMALL
INT;Usedlodeclareintegerswith a precisionuptoJSdecimal digits.PLSJNTEGER
PLS
INTEGER
typecansloresigned integersinrangefrom-JI47483647
to+2147-163647.pls_integer
datatypeismoreefficientlhannumber
datatype sincePl,S_:w"?tf:G?:^ values23