Tải bản đầy đủ
Lab 19.2: Passing Parameters IN and OUT of Procedures

Lab 19.2: Passing Parameters IN and OUT of Procedures

Tải bản đầy đủ

PassingofConstraints(DataTypes)withParameterValues
Formalparametersdonotrequireconstraintsonthedatatype.Forexample,insteadof
specifyingaconstraintsuchasVARCHAR2(60),youcanjustissueVARCHAR2against
theparameternameintheformalparameterlist.Theconstraintispassedwiththevalue
whenacallismade.
MatchingActualandFormalParameters
Twomethodscanbeusedtomatchactualandformalparameters:positionalnotationand
namednotation.Positionalnotationissimplyassociationbyposition;thatis,theorderof
theparametersusedwhenexecutingtheprocedurematchestheorderintheprocedure’s
headerexactly.Namednotationisexplicitassociationusingthesymbol=>.Ithasthe
followingsyntax:
Clickheretoviewcodeimage
formal_parameter_name=>argument_value

Innamednotation,theorderdoesnotmatter.Ifyoumixnotation,however,youshould
listthepositionalnotationbeforethenamednotation.
Defaultvaluescanbeusedifacalltotheprogramdoesnotincludeavalueinthe
parameterlist.Notethatitmakesnodifferencewhichstyleisused;bothworkinsimilar
fashion.
ForExamplech19_2.sql
Clickheretoviewcodeimage
CREATEORREPLACEPROCEDUREfind_sname
(i_student_idINNUMBER,
o_first_nameOUTVARCHAR2,
o_last_nameOUTVARCHAR2
)
AS
BEGIN
SELECTfirst_name,last_name
INTOo_first_name,o_last_name
FROMstudent
WHEREstudent_id=i_student_id;
EXCEPTION
WHENOTHERS
THEN
DBMS_OUTPUT.PUT_LINE(‘Errorinfindingstudent_id:
’||i_student_id);
ENDfind_sname;

Thisproceduretakesinastudent_idviatheparameternamedi_student_id.It
passesouttheparameterso_first_nameando_last_name.Theprocedureisa
simpleSELECTstatementthatretrievesthefirst_nameandlast_namefromthe
STUDENTtablewhenthestudent_idmatchesthevalueofi_student_id,whichis
theonlyINparameterthatexistsintheprocedure.Tocalltheprocedure,avaluemustbe
passedinforthei_student_idparameter.
ForExamplech19_3.sql

Clickheretoviewcodeimage
DECLARE
v_local_first_namestudent.first_name%TYPE;
v_local_last_namestudent.last_name%TYPE;
BEGIN
find_sname
(145,v_local_first_name,v_local_last_name);
DBMS_OUTPUT.PUT_LINE
(‘Student145is:‘||v_local_first_name||
’‘||v_local_last_name||’.’
);
END;

Whencallingtheprocedurefind_sname,avalidstudent_idshouldbepassedin
forthei_student_id.Ifitisnotavalidstudent_id,anexceptionwillberaised.
Twovariablesmustalsobelistedwhencallingtheprocedure.Thesevariables,
v_local_first_nameandv_local_last_name,areusedtoholdthevaluesof
theparametersthatarebeingpassedout.Aftertheprocedurehasbeenexecuted,thelocal
variableswillhavevaluesandcanthenbedisplayedwithaDBMS_OUTPUT.PUT_LINE
statement.

Summary
Inthischapter,youlearnedhowtocreateprocedures.First,yousawhowtocreateabasic
procedurethathasnoparameters.Then,inthesecondpartofthechapter,yousawhowto
addparameterstotheproceduretonarrowthetransactionprocesstakingplacewithinthat
procedure.
BytheWay
Thecompanionwebsiteprovidesadditionalexercisesandsuggestedanswers
forthischapter,withdiscussionrelatedtohowthoseanswersresulted.The
mainpurposeoftheseexercisesistohelpyoutestthedepthofyour
understandingbyutilizingalloftheskillsthatyouhaveacquiredthroughout
thischapter.

20.Functions
Inthischapter,youwilllearnabout
CreatingFunctions
UsingFunctionsinSQLStatements
OptimizingFunctionExecutioninSQL
Afunctionthatisstoredinthedatabaseismuchlikeaprocedure,inthatitisanamed
PL/SQLblockthatcantakeparametersandbeinvoked.Therearekeydifferencesbothin
thewayitiscreatedandhowitisused,however.Inthisshortchapter,youwilllearnthe
basicsofhowtocreate,use,anddropafunction.InChapter21,youwilllearnhowto
extendfunctionswhentheyareplacedintopackages.

Lab20.1:CreatingFunctions
Afterthislab,youwillbeableto
CreateStoredFunctions
MakeUseofFunctions
Functionsareanothertypeofstoredcodeandareverysimilartoprocedures.The
significantdifferencebetweenthetwoisthatafunctionisaPL/SQLblockthatreturnsa
singlevalue.Functionscanacceptone,many,ornoparameters,buttheymusthavea
returnclauseintheirexecutionsection.Thedatatypeofthereturnvaluemustbedeclared
intheheaderofthefunction.Afunctionisnotastand-aloneexecutableinthesameway
thataprocedureis;thatis,afunctionmustalwaysbeusedinsomecontext.Youcanthink
ofitasequivalenttoasentencefragment.Afunctionproducesoutputthatneedstobe
assignedtoavariable,oritcanbeusedinaSELECTstatement.

CreatingStoredFunctions
Thissectioncoversthebasicfunctionsyntaxanddemonstrateshowtocreateafunction.
Thesyntaxforcreatingafunctionisasfollows:
Clickheretoviewcodeimage
CREATE[ORREPLACE]FUNCTIONfunction_name
(parameterlist)
RETURNdatatype
IS
BEGIN

RETURN(return_value);
END;

Thefunctiondoesnotnecessarilyhaveanyparameters,butitmusthaveaRETURN
valuedeclaredintheheader,anditmustreturnvaluesforallofthepossibleexecution

streams.TheRETURNstatementdoesnothavetoappearasthelastlineofthemain
executionsection,andtheremaybemorethanoneRETURNstatement(thereshouldbea
RETURNstatementforeachexception).AfunctionmayhaveIN,OUT,orINOUT
parameters—althoughyouwillrarelyseeanythingexceptINparameters,becauseitisbad
programmingpracticetousetheotherparameters.
Thefollowingexampleshowsthescriptforcreatingafunctionnamed
show_description.
ForExamplech20_1.sql
Clickheretoviewcodeimage
CREATEORREPLACEFUNCTIONshow_description
(i_course_nocourse.course_no%TYPE)
RETURNvarchar2
AS
v_descriptionvarchar2(50);
BEGIN
SELECTdescription
INTOv_description
FROMcourse
WHEREcourse_no=i_course_no;
RETURNv_description;
EXCEPTION
WHENNO_DATA_FOUND
THEN
RETURN(‘TheCourseisnotinthedatabase’);
WHENOTHERS
THEN
RETURN(‘Errorinrunningshow_description’);
END;

WhenthefunctionhasbeencreatedinSQLDeveloper,thefollowingmessagewillbe
displayedinthescripteditor:
Clickheretoviewcodeimage
FUNCTIONSHOW_DESCRIPTIONcompiled

Thismessageindicatesthatthefunctionwassuccessfullycompiled.Itcanalsobeenseen
intheFunctionnodeoftheDatabaseObjectsinSQLDeveloper.SeeFigure20.1.

Figure20.1Show_DescriptionFunctionasseeninSQLDeveloper
Theexample’sfunctionheadingindicatesthatthefunctiontakesinaparameterofthe
numberdatatypeandreturnsaVARCHAR2.ThefunctionmakesuseofaVARCHAR2(5)
variablecalledv_description.Itgivesthisvariablethevalueofthedescriptionofthe
course,whosenumberispassedintothefunction.Thereturnvalueisthenthevariable.
Therearetwoexceptionsinthefunction.ThefirstistheWHENNO_DATA_FOUND
exception,whichistheonemostlikelytooccur.Thesecondexception,WHENOTHERS,
whichisusedasacatchallforanyothererrorthatmayoccur.
TheRETURNclauseisoneofthelaststatementsinthefunction.Thereasonforthis
positioningisthattheprogramfocuswillreturntothecallingenvironmentoncethe
RETURNclauseisissued.
Thefollowingexampledemonstratesthesyntaxforcreatingafunctionnamed
id_is_good.TheoutputreturnedinthisexampleisaBooleanvalue.

ForExamplech20_2.sql
Clickheretoviewcodeimage
CREATEORREPLACEFUNCTIONid_is_good
(i_student_idINNUMBER)
RETURNBOOLEAN
AS
v_id_cntNUMBER;
BEGIN
SELECTCOUNT(*)
INTOv_id_cnt
FROMstudent
WHEREstudent_id=i_student_id;
RETURN1=v_id_cnt;
EXCEPTION
WHENOTHERS
THEN
RETURNFALSE;
ENDid_is_good;

Thefunctionid_is_goodcheckswhethertheIDpassedinexistsinthedatabase.It
takesinanumber(whichisassumedtobeastudentID)andreturnsaBOOLEANvalue.
Thefunctionusesthevariablev_id_cntasameanstoprocessthedata.TheSELECT
statementobtainsacountofthenumberofstudentswiththenumericvaluethatwas
passedin.Ifastudentisfoundinthedatabase,usingthestudent_idastheprimary
key,thevalueofv_id_cntwillbe1.Ifthestudentisnotinthedatabase,theSELECT
statementpassesthefocustotheexception-handlingsection,wherethefunctionreturnsa
valueofFALSE.ThefunctionmakesuseofaveryinterestingmethodtoreturnTRUE.If
thestudentisinthedatabase,thenv_id_cntwillequal1,sothecodeRETURN1=
v_id_cntwillactuallyreturnavalueofTRUE.

MakingUseofFunctions
Thissectiondemonstrateshowtomakeuseofthestoredfunctionshow_description
thatwascreatedinthelastsection.Thefollowingexampledemonstrateshowtocallthe
storedfunctionshow_descriptioninaPL/SQLblock.
ForExamplech20_3.sql
Clickheretoviewcodeimage
SETSERVEROUTPUTON
DECLARE
v_descriptionVARCHAR2(50);
BEGIN
v_description:=show_description(&sv_cnumber);
DBMS_OUTPUT.PUT_LINE(v_description);
END;

AlexicalparameterinthePL/SQLblockof&cnumbercausestheusertobeprompted
asfollows:
Entervalueforcnumber:

InSQLDeveloper,apop-upwindowwillbedisplayed,whichrequeststhattheuser
enteravalueforthesubstitutionvariable,asshowninFigure20.2.

Figure20.2EnterSubstitutionDialogBoxinSQLDeveloper
Ifyouenter“350,”youwillsee“JavaDeveloperII”intheDBMSOutputwindowof
SQLDeveloper.IntheScriptOutputwindow,youwillseetheoldversionofthescript
withthesubstitutionvariable&sv_cnumberandthenyouwillseethenewversionof
thescriptwherethesubstitutionvariable&sv_cnumberhasbeenreplacedby350.See
Figure20.3.

Figure20.3ExecutionofFunctionShow_Description
WhenthisscriptisruninSQL*Plus,youwillseethefollowingoutput:
Clickheretoviewcodeimage
old4:v_descript:=show_description();
new4:v_descript:=show_description(350);

JavaDeveloperII
PL/SQLproceduresuccessfullycompleted.

Thismessagemeansthatthevaluefor&sv_cnumberhasbeenreplacedwith350.The
functionshow_descriptionreturnsaVARCHAR2value,whichisthecourse
descriptionforthecoursenumberthatispassedin.ThePL/SQLblockinitializesthevalue
ofv_descriptionwiththevaluereturnedbytheshow_descriptionfunction.
ThisvalueisthendisplayedwiththeDBMS_OUTPUTpackage.
Thefollowingexampleisananonymousblockthatmakesuseofthefunction
id_is_good.
ForExamplech20_4.sql
Clickheretoviewcodeimage
DECLARE
V_idnumber;
BEGIN
V_id:=&id;
IFid_is_good(v_id)
THEN
DBMS_OUTPUT.PUT_LINE
(‘StudentID:‘||v_id||’isavalid.’);
ELSE
DBMS_OUTPUT.PUT_LINE
(‘StudentID:‘||v_id||’isnotvalid.’);
ENDIF;
END;

ThisPL/SQLblockevaluatesthereturnfromthefunctionandthendetermineswhich
outputtoproject.Becausethefunctionid_is_goodreturnsaBooleanvalue,theeasiest
waytomakeuseofthisfunctionistorunitandusetheresult(whichwillbeeitherTRUE
orFALSE)inanIFstatement.WhentestingtheBooleanfunctionid_is_good,theline
IFid_is_good(v_id)meansthatifthefunctionid_is_goodforthevariable
resultsinareturnofTRUE,anothersetofstatementswillbeexecuted.TheELSEclause
coverswhatwillhappenifthefunctionreturnsFALSE.

Lab20.2:UsingFunctionsinSQLStatements
Afterthislab,youwillbeableto
InvokeFunctionsinSQLStatements
WriteComplexFunctions

InvokingFunctionsinSQLStatements
FunctionsreturnasinglevalueandcanbeveryusefulinaSELECTstatement.In
particular,theycanhelpyouavoidrepeatedcomplexSQLstatementswithinaSELECT
statement.Thefollowingstatementdemonstratestheuseoftheshow_description
functioninaSELECTstatementforeverycourseintheCOURSEtable:
Clickheretoviewcodeimage

SELECTcourse_no,show_description(course_no)
FROMcourse;

ItisidenticaltothefollowingSELECTstatement:
Clickheretoviewcodeimage
SELECTcourse_no,description
FROMcourse;

FunctionscanalsobeusedinaSQLstatement.Infact,youhavebeenusingthemall
along;youjustmightnothaverealizedit.Asasimpleexample,imagineusingthe
functionUPPERinaSELECTstatement:
Clickheretoviewcodeimage
SELECTUPPER(‘bill’)FROMDUAL;

TheOracle-suppliedfunctionUPPERreturnstheuppercasevalueoftheparameterthat
waspassedin.
Forauser-definedfunctiontobecalledinaSQLexpression,itmustbeaROWfunction,
notaGROUPfunction,andthedatatypesmustbeSQLdatatypes.Thedatatypescannot
bePL/SQLdatatypeslikeaBooleanvalue,table,orrecord.Additionally,thefunctionis
notallowedtoincludeanyDMLstatements(INSERT,UPDATE,DELETE).
TouseafunctioninaSQLSELECTstatement,thefunctionmusthaveacertainlevelof
purity,whichisaccomplishedwiththePRAGMARESTRICT_REFERENCESclause.This
topicisdiscussedindetailinChapter21inthecontextoffunctionswithinpackages.

WritingComplexFunctions
ThissectionintroducesamorecomplexfunctionthatwillbeusedinChapter21on
packages.Asthefollowingexampledemonstrates,functionscanbecomeveryelaborate
andcomplex.
ForExamplech20_5.sql
Clickheretoviewcodeimage
CREATEORREPLACEFUNCTIONnew_instructor_id
RETURNinstructor.instructor_id%TYPE
AS
v_new_instidinstructor.instructor_id%TYPE;
BEGIN
SELECTINSTRUCTOR_ID_SEQ.NEXTVAL
INTOv_new_instid
FROMdual;
RETURNv_new_instid;
EXCEPTION
WHENOTHERS
THEN
DECLARE
v_sqlerrmVARCHAR2(250)
:=SUBSTR(SQLERRM,1,250);
BEGIN
RAISE_APPLICATION_ERROR(-20003,
‘Errorininstructor_id:‘||v_sqlerrm);
END;