Tải bản đầy đủ
Lab 3.1: DML Statements in PL/SQL

Lab 3.1: DML Statements in PL/SQL

Tải bản đầy đủ

InitializeVariableswithSELECTINTO
InPL/SQL,therearetwomainmethodsofgivingvaluestovariablesinaPL/SQLblock.
Thefirstone,whichyoulearnedinChapter1,isinitializationwiththe“:=”syntax.Inthis
labwewilllearnhowtoinitializeavariablewithaselectstatementbymakinguseofthe
SELECTINTOsyntax.
AvariablethathasbeendeclaredinthedeclarationsectionofthePL/SQLblockcan
laterbegivenavaluewithaselectstatement.Thecorrectsyntaxisasfollows:
SELECTitem_name
INTOvariable_name
FROMtable_name;

Notethatanysinglerowfunctioncanbeperformedontheitemtogivethevariablea
calculatedvalue.
ForExamplech03_1a.sql
Clickheretoviewcodeimage
SETSERVEROUTPUTON
DECLARE
v_average_costVARCHAR2(10);
BEGIN
SELECTTO_CHAR(AVG(cost),‘$9,999.99’)
INTOv_average_cost
FROMcourse;
DBMS_OUTPUT.PUT_LINE(‘Theaveragecostofa‘||
‘courseintheCTAprogramis‘||
v_average_cost);
END;

Inthisexample,avariableisgiventhevalueoftheaveragecostofacourseinthe
coursetable.First,thevariablemustbedeclaredinthedeclarationsectionofthe
PL/SQLblock.Inthisexample,thevariableisgiventhedatatypeofVARCHAR2(10)
becauseofthefunctionsusedonthedata.Theselectstatementthatwouldproducethis
outcomeinSQL*Pluswouldbe
Clickheretoviewcodeimage
SELECTTO_CHAR(AVG(cost),‘$9,999.99’)
FROMcourse;

TheTO_CHARfunctionisusedtoformatthecost;indoingthis,thenumberdatatypeis
convertedtoacharacterdatatype.Oncethevariablehasavalue,itcanbedisplayedtothe
screenusingthePUT_LINEprocedureoftheDBMS_OUTPUTpackage.Theoutputofthis
PL/SQLblockwouldbe:
Clickheretoviewcodeimage
TheaveragecostofacourseintheCTAprogram
is$1,198.33
PL/SQLproceduresuccessfullycompleted.

InthedeclarationsectionofthePL/SQLblock,thevariablev_average_costis
declaredasavarchar2.Intheexecutablesectionoftheblock,thisvariableisgiventhe
valueoftheaveragecostfromthecoursetablebymeansoftheSELECTINTOsyntax.

TheSQLfunctionTO_CHARisissuedtoformatthenumber.TheDBMS_OUTPUT
packageisthenusedtoshowtheresulttothescreen.

UsingtheSELECTINTOSyntaxforVariableInitialization
ThepreviousPL/SQLblockmayberearrangedsotheDBMS_OUTPUTsectionisplaced
beforetheSELECTINTOstatement.
ForExamplech03_1a.sql
Clickheretoviewcodeimage
SETSERVEROUTPUTON
DECLARE
v_average_costVARCHAR2(10);
BEGIN
DBMS_OUTPUT.PUT_LINE(‘Theaveragecostofa‘||
‘courseintheCTAprogramis‘||
v_average_cost);
SELECTTO_CHAR(AVG(cost),‘$9,999.99’)
INTOv_average_cost
FROMcourse;
END;

Youwillthenseethefollowingresult:
Clickheretoviewcodeimage
TheaveragecostofacourseintheCTAprogramis
PL/SQLproceduresuccessfullycompleted.

Thevariablev_average_costwillbesettoNULLwhenitisfirstdeclared.Because
theDBMS_OUTPUTsectionprecedesthepointatwhichthevariableisgivenavalue,the
outputforthevariablewillbeNULL.AftertheSELECTINTOstatement,thevariable
willbegiventhesamevalueasintheoriginalblock,butitwillnotbedisplayedbecause
thereisnotanotherDBMS_OUTPUTlineinthePL/SQLblock.
DataDefinitionLanguage(DDL)statementsarenotvalidinasimplePL/SQLblock
(moreadvancedtechniquessuchasproceduresintheDBMS_SQLpackagewillenableyou
tomakeuseofDDL),yetdatamanipulation(usingDataManipulationLanguage[DML])
iseasilyachievedeitherbyusingvariablesorbysimplyputtingaDMLstatementintoa
PL/SQLblock.HereisanexampleofaPL/SQLblockthatupdatesanexistingentryinthe
zipcodetable.
ForExamplech03_2a.sql
SETSERVEROUTPUTON
DECLARE
v_cityzipcode.city%TYPE;
BEGIN
SELECT‘COLUMBUS’
INTOv_city
FROMdual;
UPDATEzipcode
SETcity=v_city
WHEREZIP=43224;
END;

ItisalsopossibletoinsertdataintoadatabasetableinaPL/SQLblock,asshowninthe
followingexample.
ForExamplech03_3a.sql
Clickheretoviewcodeimage
DECLARE
v_zipzipcode.zip%TYPE;
v_userzipcode.created_by%TYPE;
v_datezipcode.created_date%TYPE;
BEGIN
SELECT43438,USER,SYSDATE
INTOv_zip,v_user,v_date
FROMdual;
INSERTINTOzipcode
(ZIP,CREATED_BY,CREATED_DATE,MODIFIED_BY,
MODIFIED_DATE
)
VALUES(v_zip,v_user,v_date,v_user,v_date);
END;

BytheWay
SELECTstatementsinPL/SQLthatreturnnorowsortoomanyrowswill
causeanerrortooccurthatcanbetrappedbyusinganexception.Youwill
learnmoreabouthandlingexceptionsinChapters8,9,and10.

UsingDMLinaPL/SQLBlock
ThissectiondemonstrateshowDMLisusedinPL/SQL.ThefollowingPL/SQLblock
insertsanewstudentintothestudenttable.
ForExamplech03_4a.sql
Clickheretoviewcodeimage
BEGIN
SELECTMAX(student_id)
INTOv_max_id
FROMstudent;
INSERTintostudent
(student_id,last_name,zip,
created_by,created_date,
modified_by,modified_date,
registration_date
)
VALUES(v_max_id+1,‘Rosenzweig’,
11238,‘BROSENZ‘,‘01-JAN-2014’,
‘BROSENZ’,‘10-JAN-2014’,‘15-FEB-2014’
);
END;

TogenerateauniqueID,themaximumstudent_idisselectedintoavariableand
thenincrementedby1.Inthisexample,thereisaforeignkeyonthezipiteminthe
studenttable,whichmeansthattheZIPcodeyouchoosetoentermustbeinthezipcode
table.

UsinganOracleSequence
AnOraclesequenceisanOracledatabaseobjectthatcanbeusedtogenerateunique
numbers.Youcanusesequencestogenerateprimarykeyvaluesautomatically.
AccessingandIncrementingSequenceValues
Onceasequenceiscreated,youcanaccessitsvaluesinSQLstatementswiththese
pseudocolumns:
CURRVAL:Returnsthecurrentvalueofthesequence.
NEXTVAL:Incrementsthesequenceandreturnsthenewvalue.
Thefollowingexamplecreatesthesequenceeseq.
ForExample
CREATESEQUENCEeseq
INCREMENTBY10

ThefirstreferencetoESEQ.NEXTVALreturns1.Thesecondreturns11.Eachsubsequent
referencewillreturnavalue10greaterthantheoneprevious.
(Eventhoughyouwillbeguaranteeduniquenumbers,youarenotguaranteed
contiguousnumbers.Insomesystemsthismaybeaproblem—forexample,when
generatinginvoicenumbers.)
DrawingNumbersfromaSequence
Asequencevaluecanbeinserteddirectlyintoatablewithoutfirstselectingit.(Inveryold
versionsofOraclepriortoOracle7.3,itwasnecessarytousetheSELECTINTOsyntax
andputthenewsequencenumberintoavariable;youcouldtheninsertthevariable.)
Forthisexample,atablecalledtest01willbeused.Thetabletest01isfirst
created,followedbythesequencetest_seq.Thenthesequenceisusedtopopulatethe
table.
ForExamplech03_5a.sql
Clickheretoviewcodeimage
CREATETABLEtest01(col1number);
CREATESEQUENCEtest_seq
INCREMENTBY5;
BEGIN
INSERTINTOtest01
VALUES(test_seq.NEXTVAL);
END;
/
Select*FROMtest01;

UsingaSequenceinaPL/SQLBlock
Inthisexample,aPL/SQLblockisusedtoinsertanewstudentinthestudenttable.
ThePL/SQLcodemakesuseoftwovariables,USERandSYSDATE,thatareusedinthe
selectstatement.Theexistingstudent_id_seqsequenceisusedtogenerateaunique
IDforthenewstudent.
ForExamplech03_6a.sql
Clickheretoviewcodeimage
DECLARE
v_userstudent.created_by%TYPE;
v_datestudent.created_date%TYPE;
BEGIN
SELECTUSER,sysdate
INTOv_user,v_date
FROMdual;
INSERTINTOstudent
(student_id,last_name,zip,
created_by,created_date,modified_by,
modified_date,registration_date
)
VALUES(student_id_seq.nextval,‘Smith’,
11238,v_user,v_date,v_user,v_date,
v_date
);
END;

InthedeclarationsectionofthePL/SQLblock,twovariablesaredeclared.Theyare
bothsettobedatatypeswithinthestudenttableusingthe%TYPEmethodof
declaration.Thisensuresthedatatypesmatchthecolumnsofthetablesintowhichthey
willbeinserted.Thetwovariablesv_userandv_datearegivenvaluesfromthe
systembymeansofSELECTINTOstatements.Thevalueofthestudent_idis
generatedbyusingthenextvalueofthestudent_id_seqsequence.

Lab3.2:TransactionControlinPL/SQL
Afterthislab,youwillbeableto
UsetheCOMMIT,ROLLBACK,andSAVEPOINTStatements
PutTogetherDMLandTransactionControl

UsingCOMMIT,ROLLBACK,andSAVEPOINT
Transactionsareameanstobreakprogrammingcodeintomanageableunits.Grouping
transactionsintosmallerelementsisastandardpracticethatensuresanapplicationwill
saveonlycorrectdata.Initially,anyapplicationwillhavetoconnecttothedatabaseto
accessthedata.WhenauserisissuingDMLstatementsinanapplication,however,these
changesarenotvisibletootherusersuntilaCOMMITorROLLBACKhasbeenissued.The
Oracleplatformguaranteesaread-consistentviewofthedata.Untilthatpoint,alldatathat
havebeeninsertedorupdatedwillbeheldinmemoryandwillbeavailableonlytothe
currentuser.Therowsthathavebeenchangedwillbelockedbythecurrentuserandwill
notbeavailableforupdatingtootherusersuntilthelockshavebeenreleased.ACOMMIT
orROLLBACKstatementwillreleasetheselocks.Transactionscanbecontrolledmore
readilybymarkingpointsofthetransactionwiththeSAVEPOINTcommand.
COMMIT:Makeseventswithinatransactionpermanent.
ROLLBACK:Eraseseventswithinatransaction.
Additionally,youcanuseaSAVEPOINTtocontroltransactions.Transactionsare
definedinthePL/SQLblockfromoneSAVEPOINTtoanother.Theuseofthe
SAVEPOINTcommandallowsyoutobreakyourSQLstatementsintounitssothatina
givenPL/SQLblock,someunitscanbecommitted(savedtothedatabase),otherscanbe
rolledback(undone),andsoforth.
BytheWay
TheOracleplatformmakesadistinctionbetweenatransactionandaPL/SQL
block.ThestartandendofaPL/SQLblockdonotnecessarilymeanthestart
andendofatransaction.
Todemonstratetheneedfortransactioncontrol,wewillexamineatwo-stepdata
manipulationprocess.SupposethatthefeesforallcoursesintheCTAdatabasethathavea
prerequisitecourseneedtobeincreasedby10percent;atthesametime,allcoursesthat
donothaveaprerequisiteneedtobedecreasedby10percent.Thisisatwo-stepprocess.
Ifthefirststepissuccessfulbutthesecondstepisnot,thenthedataconcerningcourse
costwouldbeinconsistentinthedatabase.Becausethisadjustmentisbasedonachange
inpercentage,therewouldbenowaytotrackwhichpartofthiscourseadjustmentwas
successfulandwhichpartwasnot.
Inthefollowingexample,onePL/SQLblockperformstwoupdatesonthecostitemin
thecoursetable.Inthefirststep(thiscodeiscommentedforthepurposeof
emphasizingeachupdate),thecostisupdatedwithacostthatis10percentlesswhenever
thecoursedoesnothaveaprerequisite.Inthesecondstep,thecostisincreasedby10
percentwheneverthecoursehasaprerequisite.
ForExamplech03_7a.sql
Clickheretoviewcodeimage
BEGIN
—STEP1