PUSQL
provides variousbuilt-inmethodsthatmake
iteasytousecollections.These methods canbefunctions,suchasexists
andcount
or aprocedure,such asextend, trim, and delete. There aresome
limitationwithbuilt-incollectionmethods,suchas they can notbe calledbyusingSQL
statements;EXTEND
andTRIM
methodscan notbeused withassociative arrays.Table6.2givesyouabriefdescriptionofvariousbuilt-incollectionmethods.Dsscription
Hmnnflw
auatwaftaioiuat«cilitUna.Haturotha anallMtImIma«n>bar
m
acalialonDatum
thebigotMm
flunk* celacnaa.Ratnmtha kidM
—
harttatarecadaaMax
a.h
atalaeilati,kicnMMithaall*of*COUNtlBn.
Trimafdvenanatillaiza of cafecnoii.
Oakftai
db
abwatiIroncaMta.
Let'sdiscuss thesemethodsin detail.
EXISTS
This is a function, which either returns
TRUE
or FALSE. Ifany specified element, say nth element,existsinthecollection,thenit-returns'true';otherwise,itreturns'false'.When
the nth elementisout ofrange,then itreturnsFALSE
ratherthanraisinganexception. ThismethodisusedToavoid the referencingofnon-existentelements. SeeListing6.12tounderstand
how
itworks.
Listing6.12;PI75QL programtouse
EXISTS
function121
In Listing6.12, we;have usedthe
exists
method in 'lievarrayandncsied table tocheck existenceoitheelemenlwhosesubscripthasbeenpassedasparameterm
thismethod.We haw
usedtheIF.-- ELSE:controlstatement10display[heouipulonihe basisofme
existenceandnr>ri-exis!erit.eui Iheelement.
Outpulof ListingbA2isasfollows:
COUNT
The
COUNT
function returnsthenumberufek'menlsthat currencyexi^lin auilledion. This methodisvervusefulwhen
youdonotknow
theexactnumberofelementsinacollection.See Listingfc.JJtounderstandItsworking.Listing6,13:PL/SQL programtouse
COUNT
functionInLisling6.1 3,Ihe
COUNT
melhodisusedtocalculateIhenumberofelementsinvarray
andnested
-dbLe.Outputof ListingbAiisasfollows:
You cm
usethismethodwhere;integervalueisespetled 122PUSQL
CollectionsandRecordsfunctionreturnsthenumberofelementsthaia varraycancontain.Inolderwords, returnsiheupperboundof avarray.Incaseofnestedtablesandassociativearrays, functionreturnsNull.This meihod can beusedwhereveran integervalueisexpected.
6.14shows
how
thisfunctionworks:14:
PUSQL
programlauseLIMIT
functiontheprecedinglisting, first
we
havedisplayed thetotal numberofelementsinvarray,andthen tolaInumber
ofelementsthatavarraycan conla in.Theoutputof Listingb.i4isasfollows:ofIhemarefunctions,
FIRST
returnsthesmalEe$isubscriptin[he collection,and[helast
returns Ihe last subscript in the collection. Ifthe collection isempty, then these returnnull.
varrays,
FIRST
alwaysreturns1,butforNesredtable,itmay
ormay
norreturns1;ilthefirsthas alreadybeendeletedfromthenestedtablerthen the
first
function returns2.,the
LAST
functionreturnstheupperboundincaseofvarrays;butincase ofnesteditgivesThesameresultasthe
COUNT
function. Ifyoudeletesome
elements fromthe nestedtable,thenthevalue returnedby thelast
funciionismorethanihevalueitreturnswithofassociativearrayswithvarchar.2keyvalues,these functionsreturnIhe lowesTand
VARCHAB2
keyvalues. Listing6.35showshow
these functionswork.6.15:
PUSQL
programtouseFIRST
andLAST
functions123
In Listing 6,15,the
first
andthelast
methodsare usedToiteratetheloopinandthen the smallestandlargestsubscriptsof thenestedtableare displayed, deleted Ihefirst element from the nestedtableby using the
delete
method;startingsubscriptisdisplayedonceagain.
Theoutput ofListing6.15isasfollows:
PRIOR
(n)and NEXT(n)
Both these functions return the subscriptsof thespecified element.
PRIOR
{n) returnsthe subscript of theelementthatprecedes index ninthaicollection:whileIhenext
methodreturns thesubscriptof[heelementthatsucceeds index n ofacollection.prior
(n) returnsnull,ifn hasnopredecessorandNEXT
(n) relurnsnullwhen
ithasnosuccessor.Incase, associativearrays have
dements
oflypi' ^.'ARCHA^, Thi-'&elunctiun*return thekey valuescorrespondingtothespecifiedclement. Lining6.16showstheuse of thePRIOR
Jn)and theNEXT
mlmethods.Listing6.16;PL/5QL programtouse
PRIOR
andNEXT
functionsEXTEND
Thisisaprocedure,whichisusedloincrease[hesize ofacollection.Thismethodcan notbe usedincase ofjssehMlivearrays Tins melhod unlvlieu%ed wiihtdleUiunslhat have alreadybeeninitializcdLVol canuseibisprocedureinihefollowingthreewavs1
EXTEND:
Itappendsonenullelemenliothe colleclion.EXTEND
(n):liappendsnnullelcmenlsIoIhecollection.EXTEND
(n,I):Itappendstheithelementntimesinthe colleclion.AU „ _
Ifa cotecttonhasNOT NULLconflrainTthenmilvaluescannotbe appendedInacdfctiorv
Listing6.18shows
how
iheEXTEND
procedure works.Listing6.18:HL/SQL programtouse
EXTEND
functionIn Listing GJ8,
we
have used iheextend
methodm
all threeways—
lhai 15, withoutany parameter, withsingleparameter(2),andwilhIwoparameters(2,3).We
have usedtheCOUNT
methodafteriheEXTEND
methodtodisplay Ihelotal numberof elementsinIhecolleclion (hereHisavarray)eachtime Ihe elementsareextended.Theoutputof Listing6.18isasfollows:
126
Chaplet6jUnderstanding
PUSQL
Collectionsn"dRecordsTBIM
trim
deletes the elementsfrom theendo£thecollection.Thismethodcan be used inthe followingways:TRIM:11deletesasingleelementfromIheendofacollection.
TRIM
(n):Itdeletesnnumberofelements fromtheendof acollection.Ifnismorethan the numberofelements containedinacollection,thenitraisesSUBSCRIPT_BE¥0ND_COUNT
exception.Listing6.19showshow
itworks.Listing6.19tPL/SQL programtouse
trim
functionInLisiing6.19,first
we
havedisplayed thetotalnumberofelementsinthenesiedtablebyusingCOUNT
method,andthenwe
have trimmedthenestedTablebyone elementusing thetrim
method.After thatwe
haveagain applied IheCOUNT
method onthenestedtable.At lastH
we
have trimmedthenestedtableonceagainbyusingTRIM
methodwith parameter.Theoutput ofListing6.19isasfollows;
DELETE
DELETE
isaprocedure,anditisusedtodefeleelementsfromacollection.Thismethod cannot beappliedon the varraycollection type. UsingtheDELETE
procedure, unlikeTRIM
which deleteselementsfromtheendofthe collection,youcandeleteanyspecifiedelementfroma collection.Thisprocedurecanbeusedinthefollowingways:
DELETE:Itremovesallelementsfromacollection.
DELETE(n): Itremovesthe nlhelementfroma nested tableorassociative array with a numeric key. If the associative array has elements of string type, then the element corresponding|othatstringtypeisdeleted.Thismeihoddoes nothingifnisnulL
127
J
DELETE (mPn);Itremovesallelementsiniherangem
tonIroinaeorteelion- ihh methodwilldonothingit
m
islargerthan n ortheyarenull.Listingh.JO showshow
iiworks.Listing6.20: f'L'SQI program(nuse"ELET/.Ilihetion
S0.L> SET SFRvEROUTPlfT ON DECLARE
type esal tableof nuhber C?) nqt NULL;
—
Defining nested table collection C esal; -- Declaring nested table collection variableBEGIN
c := esal {SOOQ, 5500,6000, 6500,4500);
-
initializing nesteduble
DBMS_QUTPUT.PUT_LINE (' Total number of elements innested table is ' ||
COUNT)
;
crdelete W):
—
U5in.gDelete wi th singleparameterohhs._output.PuT_LlNE (' Total number of elements after removing second element is ' 11 C.COUNT);
Crdelete (3, 5): using deletewith specific range of parameters DBMS_OUTPUTLPUT_LlNE (' Total numberof elements after removing rangeof element is ' II C.COUNT);
c.delete: -- using deletewithout parameter dbm5_output.put_line (
H Total number ofelements after using delete without parameteris ' |[
count);
end;
/
InListingf>.J<Kur^t
ue
h.ivedisplayedthetotalnLimberofelementsm
ihenestedtablebyusinp, the•:UU:.i method,andihcridole:oil(hosecond element from ihe(able,andaji<iinapplied(hoO W.T
methodIndisplavtht11miniufelementsin.ihenestedtable.Nov*
wo
usl"ihej'-L^.\.'.. methodtoremote(he speciiic rnnjjeoielements lrumthe tableanddii.'MriuKethe."OJti'i method Similarly,
wv
ha\e.iji.iiriusedtheI. - methodwithoutanvparameterandthenihe(nuntmethodlodisplay(he
town
onceag.nn.Theoutputof Listing6,20isasInlloivj.;
Total number of elements in nested table is 5
Total number of elements after removing second elementis 4 Total number of elements after removinga range of elementis 1 Total number of elements after using delete without parameteris o PL/SQL proceduresuccessfully completed.
With this
ue
complete discussion on tolleel ions, and irsinp collection melhods. In usingcolli'ilinns