Tải bản đầy đủ

Prentice hall programming oracle triggers and stored procedures 3rd edition dec 2003 ISBN 0130850330

ChapterOne.AnIntroductionto
RelationalDatabaseTables
1.1BEFORERELATIONALTABLES
1.2SQL
1.2.1ANSIStandard
1.2.2SQLDatabase
1.2.3SQLImplementation
1.2.4SQL*Plus
1.3TABLES
1.3.1DataModelView
1.3.2CreateTableScript
1.3.3DescribingtheTable
1.3.4TableData
1.4SQLSTATEMENTS
1.4.1DataDefinitionLanguage(DDL)
1.4.2DataManipulationLanguage(DML)
1.4.3TransactionControl


1.4.4SessionControl
1.4.5SystemControl

1.5TABLECOLUMNDATATYPES
1.5.1Character
1.5.2Number
1.5.3DATETypes
1.5.4LargeObjects
1.5.5XMLType
1.5.6LONGandRAWTypes
1.5.7ROWIDType
1.6BEHINDTABLES
1.6.1ApplicationTablespaces
1.6.2DataDictionary


1.1BeforeRelationalTables
In1969,ApolloastronautsNeilArmstrongandBuzzAldrin
walkedonthemoon.ThatsameyearDr.EdgarFrankCodd,
Ph.D.,developedthetheoryforrelationaldatabasesystems.
Shortlyafterthisdevelopment,Coddpublished"ARelational
ModelofDataforLargeSharedDataBanks"intheAssociation
ofComputingMachinery(ACM)journal,Communicationsofthe
ACM.Codd'smodelbecamethefoundationforaprototype;a
relationaldatabaseprojectwithinIBMcalledSystem/R.Studies
wereperformedattheIBMSanJoseResearchCenter(nowthe
AlmadenResearchCenter)andby1974IBMhadarunning
prototyperelationaldatabasesystem.Thissystemwasbased
onmultitablequeriesandmultiuseraccess.Themethodfor
accessingdatainSystem/RwascalledStructuredEnglishQuery
Language(SEQUEL).
Followingitsresearchanddevelopment,IBMreleasedSystem/R
asaprototype.ItwasusedbytheMITSloanSchoolof
Managementandcommercialorganizationswithinthe
manufacturingandinventorysectors.Theprojectdemonstrated
thatCodd'stheoriescouldbeappliedandimplementedinthe
realworld,butendedin1979.
ThesuccessofSystem/Rdidnotreceivequitethesame
attentiontheworldgavetheApolloastronautsonJuly20,
1969;but,System/R'ssuccesscreatedanewparadigminthe
worldofinformationtechnologyaparadigmthatdominatesthe
informationagetothisday.
Coddbelievedthatprogrammersshouldbeabletocontrolthe
exactdatausedtojoinandconstructqueriesfrommultiple
independenttables.Thiswasnotthecasewithexisting
hierarchicalandnetworkdatabases.Fortheseother
technologies,anapplicationprogrammerwouldcodean
algorithmtonavigatethroughthedatabasebyaccessingdata


recordsbasedonthepredefinednavigationpaths.Assoftware
requirementschanged,programmersfrequentlyneeded
databasemodificationstothesepathsandnewnavigations
pathsneededtobedefined.Thesoftwaredevelopmentprocess
wasslowandimpairedwithfrequentmeetingsondataaccess.
Codd'smodelhadabroadimpactonthesoftwaredevelopment
process.
System/Rwasimplementedbyagroupofhighlytalentedand
educatedsoftwareengineers.Theydemonstratedthatlarge
informationsystemscouldbebuiltonCodd'stheoryofmultiindependenttablesandastructuredquerylanguage.Thiswas
thebirthofSEQUEL.ThroughouttheSystem/Rproject,
engineersopenlypublishedtheirworkintechnicaljournalsand
atinternationalconferences.Thepolicyofopenpublicationis
consideredtohavebeenafactorinthesuccessof
System/Rleadingtothecreationofmanyrelationaldatabases
suchasDB2andOracle.
IBMpassedcontroloftheSystem/Rstructuredquerylanguage
totheAmericanNationalStandardsInstitute(ANSI),aprivate
nonprofitorganizationthatadministersU.S.voluntary
technologies.Becauseoftrademarklaws,thelanguagewas
renamedfromSEQUELtoSQLfor"StructuredQuery
Language."TodaySQLisanANSIstandardandanInternational
StandardsOrganization(ISO)standard.
In1977,agroupofengineerswhohadbeenfollowingthe
System/Rproject,primarilythroughpublications,recognizedits
potentialandformedacompany.Thiscompany,Software
DevelopmentLaboratories,waslaternamedRelational
Software.Thisnewcompanydevelopedandmarketedthefirst
commercialversionofarelationaldatabasemanagement
system,whichwasbasedontheANSISQLStandard.They
namedtheirproductOracle.
WhenprojectSystem/Rendedin1979,manyinformation
systemsreliedoneitherhierarchicalornetworkdatabase


architecture.Inthe1980s,manydevelopmentprojectsmoved
towardrelationaltechnology.Today,themajorityofnew
informationsystemsarerelational;however,hierarchicaland
networkdatabaseproductshavestillmaintainedamarket
presence.
IMS/DBistheflagshiphierarchicaldatabaseofIBM.Rockwell
InternationalandIBMdevelopedIMSin1969tomanagedata
fortheNationalAeronauticsandSpaceAdministration's
(NASA's)Apolloprogram.IMS/DBcontinuestodaywithasolid
internationalpresence.Itisindustry-wideandservesan
estimated200millionendusers.TheIMS/DBdatabaseserved
theApolloprogramincludingApollo11,whichsentArmstrong,
Aldrin,andpilotMikeCollinstothemoon.
ComputerAssociates'networkdatabaseproductisCA-IDMS,a
widelyuseddatabaseserving2,000sitesaroundtheworld.The
producthaschangedinnameandownershipbutcontinuesto
supportlargecorporatedatasystemsthatrunonIBMOS/390
platforms.
IDMShasaninterestinghistory.JohnJ.Cullinanefounded
CullinetSoftware,Inc.in1968.HeboughttherightstoIDMS,a
CODASYLdatabase,fromB.F.Goodrich.CODASYL,anacronym
forConferenceonDataSystemLanguages,wasestablishedin
1960bytheDepartmentofDefenseforthepurposeof
standardizinglanguagesandsoftwareapplications.Cullinetwas
thefirstsoftwarecompanytobelistedontheNewYorkStock
Exchange.ComputerAssociatespurchasedCullinetin
Septemberof1989andrenamedtheproductCA-IDMS.
AlthoughCA-IDMSisbasedondatabasenetworkarchitecture,
theproductincludesanANSI-compliantSQLOption.Thisoption
allowsapplicationstoaccessIDMSdatausingSQL.Asetof
comprehensivetoolsisavailablethatincludesagentsfor
enterprisemonitoring,paralleltransactionprocessingusingIBM
ParallelSysplexClusterTechnology,JDBCsupportforJava,and
manyothereBusinesstechnologies.ThemajorityofIDMS


applicationsarewritteninCOBOL.
Oracle,predominatelyknownfortheRelationalEnterprise
Server,ownstwoadditionaldatabaseproducts:(a)anetwork
databaseproductcalledDBMS,whichisaCODASYLdatabase,
and(b)arelationaldatabaseproductcalledRdb.BothRdband
DBMSwerepurchasedfromDigitalEquipmentCorporation
(DEC)priortotheacquisitionofDECbyCompaq.
OracleacquiredDBMSwhenitpurchasedtheRdbproduct
familyfromDEC.KenOlsen,anMITgraduate,hisbrotherStan,
andHarlanAndersonfoundedDEC.Inadditiontohardware
architecturessuchasthePDP-11,VAX,andAlpha,DEC
developedRdb,arelationaldatabase,andalsoDBMS,a
networkdatabase.Thenetworkdatabasewasrenamedfrom
VAX/DBMStoDECDBMSwhenversionV5.0wasreleasedon
theAlphaAXPplatform.
Oracle'sCODASYLDBMSisamulti-usernetworkdatabasethat,
likeRdb,isoptimizedfortheCompaqOpenVMSoperating
systemoneitheranAlphaorVAXarchitectureplatform.DBMS
ishighlysuitedformanufacturingsystemsandshopfloor
systemsthatrequirestableenvironmentswheredatabase
informationisfairlystatic.ConsilliumCorporation'sWorkStream
isthemostwidelyinstalledManufacturingExecutionSystem
(MES)inthesemiconductorandelectronicsindustries.
WorkStreamhasalonghistoryofrunningonVAX/DBMSand
todayrunsprimarilyonVAXandAlphaserversusingOracle
CODASYLDBMS.
Rdb7wasOracle'sfirstreleaseofRdbthatwasconceivedand
engineeredasanOracleproduct.Oracle'sRdb7isanenterprise
relationaldatabaseoptimizedfordigitalplatforms;thatis,the
Hewlett-PackardCorporation'sOpenVMSoperatingsystemand
CompaqDigitalUNIX.WhenCompaqacquiredDECitreplaced
theDECversionofUNIX,calledUltrix,withtheproductname
DIGITALUNIXanoperatingsystembasedona64-bit
architecturethatrunsonAlphaAXPplatforms.


Insummary,thedatabasemarketisclearlydominatedby
relationaltechnology;however,hierarchicalandnetwork
databasescontinuetomeettheneedsofenterprisenetwork
computingenvironments.IBMIMS/DBisadominant
hierarchicaldatabasethatcanservicehigh-transactionrates
andhasalargeinstallbase.TwonetworkdatabasesCA-IDMS,
licensedbyComputerAssociates,andDBMS,licensedby
Oracle,playcriticalrolesinsupportofhigh-transaction
enterprise-widesystems.InadditiontotheOracleEnterprise
Server,OracleCorporationalsoownsRdb7,arelational
database,andDBMS,anetworkdatabasebothproductsare
optimizedforCompaqplatforms,includingAlphaAXP.Todaythe
OracleDatabaseServeraddressestheneedsofsmallandlarge
businessesthatrequireinformationprocessingforonline
transactionprocessing(OLTP)systems,decisionsupport
systems(DSS),plustheeBusinesssolutions.Thesetypesof
applicationscanoperateonsmall,stand-aloneservers,oron
distributed,high-availabilityarchitectures.


1.2SQL
SQLmeanssomethingveryspecific,whereasthetermdatabase
hasbroadmeaningandinterpretationineverydayconversation.
ThissectionelaboratesontheSQLlanguageasastandard.
TopicsincludeSQLimplementation,embeddedSQL,DirectSQL,
andSQL*PlusasanimplementationofDirectSQL.

1.2.1ANSIStandard
SQLisalanguagecurrentlydefinedinanANSIstandard(the
previoussectiondiscussedthehistoryofSQLasitpassedfrom
IBMtoANSI).IfyouarewritinganOracleapplicationthatuses
SQL,thenyouarecodingSQLstatementswhosesyntax
complieswithANSI-X3.135-1999,"DatabaseLanguageSQL."
ThisANSIstandardisavailabletothepublicthroughtheANSI
Webstore.Youcanvisitthesite,
http://webstore.ansi.org/ansidocstore/,whichhasasearch
formfield.Usingthesearchfield,youcanfindSQLstandards
withasearchon"ANSIX3.135."Youcanobtaincopiesofthis
documentinPDFformat;thecost,asofthiswriting,is$18and
itcontainsabout600pages.
Thestandard,aswithmoststandards,isdefinedusingthe
BackusNaurFormsyntaxillustratednext.Thefollowingextract,
fromANSI-X3.135-1999,"DatabaseLanguageSQL,"isshown
heretoillustratetheprecisenesswithwhichthestandard
definesthesyntaxofaCREATETABLEstatement.

::=
CREATE[{GLOBAL)LOCAL}TEMPORARY]TABLE



[ONCOMMIT{DELETEIPRESERVE}ROWS]
::=

[{}...]
::=

|
So,ifyouareadatabasevendorandyousellaSQLdatabase
product,thenyouaretellingyourcustomersthatyourdatabase
productiscapableofparsingandexecutingANSISQL
statements,suchastheaforementionedCREATETABLE
statement.
Thereisalwaysanadvantagetoworkingwithastandard.It
meansthatyourknowledgeistransferable.Anunderstandingof
SQLmeansthatyourknowledgeofrelationaldatabase
technologycantransferbetweenproductssuchasOracleand
SQLServer.Evenwithinastandardtherearedifferences.SQLis
noexception.
SQLdiffersacrossvendorsfortworeasons.First,thereare
"implementationdefined"featuresinthestandard;thatis,for
someSQLfeatures,thespecificnatureofhowafeatureis
implementedis"implementationdefined"thestandardexplicitly
statesthiswiththelanguage"implementationdefined."This
meansthevendorhasdiscretioninhowthefeatureis
implemented.Oneexampleishowthevendorimplementsthe
catalogordatadictionary.Thestandardcannotimposehowa
vendorstoresdatabasemetadata.We'llseelaterinthischapter
howOracle'sdatadictionaryisasetofrelationaltablesfrom
whichwecanselecttremendousamountsofinformation,such
asinformationdescribingthetableswecreate.
Asecondreasonwhytherearedifferencesacrossdatabasesis
duetothefactthatvendorsdoenhancetheirspecificSQL
engineswithadditionalcapabilitiesthattheyfeelbenefitthe


applicationdeveloper.OneexampleistheDECODESQLfunction
thatyouwillfindinOracle.Thisisapowerfulfunctionthatwill
notnecessarilyappearinotherdatabaseproductssimply
becauseDECODEisnotpartoftheANSIstandard.Another
exampleisthedatabasecolumntypeCURRENCYthatyoufind
inSQLServernotalldatabaseproductsprovideaCURRENCY
type.Thesedifferencesareminorcomparedtothemany
consistenciesacrossSQLproductsthatareensuredbytheANSI
standard.
Insummary,youwillfindvariationsinsomeSQLstatements
acrossdatabaseenginesthisisreallynotabigdeal.For
example,ifyoubuildyourexpertiseinSQLandyoubuildthis
knowledgeinOracle,thenyourknowledgewillincludean
understandingofinnerandouterjoins.Ifyouareever
confrontedwiththesyntaxofouterjoinsfromaSQLServeror
DB2application,wherethissyntaxvaries,thenyoucaneasily
maketheknowledgetransition.Thekeyissueistorecognize
thattherearedifferences,becauseyouarelikelytobecome
exposedtothesedifferencesatsomepointinyourcareer.
Whenthishappens,justrememberthatproductswillhave
subtledifferencesevenundertheumbrellaofanANSI
standard.

1.2.2SQLDatabase
Thetermdatabaseisusedoftenineverydaylanguage,butitis
importanttorememberthatnotall"databases"arecreated
equal.Norcantheyallbecalledrelationaldatabases.Theterm
relationaldatabasereferstoonebasedontheSQLstandard
thatiscapableofparsingandexecutingSQLstatements.We
canbeverygeneralinhowweusethetermdatabase,butthe
termrelationaldatabasedoesconveyadatabasethatisbased
ontheSQLstandardsomethingveryspecific.
Incontrasttorelationaldatabases,therearenonrelational


databases,suchasDBMS.DBMSisadatabaseproductlicensed
byOracleandisnotarelationaldatabaseitisanetwork
database.AccesstoDBMSisthroughalanguagesimilartoSQL,
butitisnotSQLperANSIstandard.Somedatabases,suchas
IDMS,arenotrelationaldatabases,yettheyprovideafrontend
thatallowsanapplicationtoaccessthedatausingSQL.Having
aSQLfront-endcapabilitydoesnotmakeIDMSarelational
database.Arelationaldatabaseisrelationalwhenitconformsto
theminimumrequirementsoftheANSISQLstandard.
OracleisafullySQL-compliantdatabase.AnOracledatabase
consistsofmanyfilesthatarepreferablydistributedacross
severaldiskpartitionsdistributingfilesminimizesIOcontention.

1.2.3SQLImplementation
GiventhatOracleisarelationaldatabaseandweaccessOracle
datausingSQL,howdoesonecreateandmanipulatethatdata?
YoucouldwriteaVisualBasic,C,Perl,orJavaprogram.You
couldwritejustaboutanyprograminanylanguageyouwant
andembedSQLstatementsinyourprogram.Thesestatements
willinsertdata,changeit,anddeleteit.Ourapplication
programscanpotentiallyexecuteanyvalidSQLstatement
againstourrelationaldatabase.
SQL,originallycalledSEQUEL,designedbyIBM,andbasedon
Codd'srelationaltheory,provideddataaccessmethodsforthe
System/Rproject.TheprimarypurposeofSQLtodayisthatwe
useitinamannersimilartowhichitwasusedbySystem/R;
thatis,tobeembeddedwithinaprogramminglanguageandto
providedataaccessmethodsagainstdatabasetablesfora
productionsystem.Onecoredifference,fromaday-to-day
codingperspective,betweenprogramsoftodayandthoseof
System/Risthatwearemorelikelytouseamorecurrent
programminglanguage,suchasJavaorC#.Secondly,
programswecodetodayutilizeenhancementstotheSQL


standardsthisincludesthekeycomponentsofthistext:
Databaseconstraints
Triggers
Storedprocedures
Supposeyoujustwanttodosomethingsimpleandquick.Let's
sayyouwanttocreateatablewithonecolumnandinsertone
rowintothattable.Forsuchasimpletask,theefforttocode
andcompileaprogramseemsexcessiveanditis.Forasimple
SQLinterfaceweusetoolsthataddressthe"directinvocationof
SQL."TheSQLstandardaddressesembeddedSQLandthisis
whathasbeendiscusseduptothispoint,embeddingSQL
statementswithincompilerlanguageprogramsbuttheSQL
standardalsoaddressesanothermethodreferredtoasDirect
SQL.Thisiswherewedothesimpleandquickstuff.
TheSQLStandardspecifiesthreeapproachestoSQL:
embeddedSQL,modularSQL,andDirectSQL.Embeddedand
modularSQLareprincipaltechniquesforapplications
developmentusingacompilerlanguagetheyaregreatfor
applicationsdevelopmentbutimpracticalforsimpletasksand
forlearningtheSQLlanguage.
IfwedidnothaveanimplementationofDirectSQLandwanted
toseealltherowsofatable,wewouldhavetowritean
applicationprogram,embedaSQLcursor,fetcheachrowinto
localvariablesandprintthosevariablesouttosomedefault
device.AtoolthatimplementsDirectSQLallowsustodisplay
thesamedatainabout5secondsmostlylimitedtohowfastwe
cantypeordrag-and-drop.Ratherthanacompiledprogram,
DirectSQLallowsustotypeaSQLSELECTstatementwhereby
allrowsareflushedtoourscreenforviewing.


TheANSIstandarddescriptionofdirectSQLisstatedinthe
following:
DirectinvocationofSQLisamechanismforexecuting
directSQL-statements,knownasstatement>s.IndirectinvocationofSQL,themethodof
invokings,themethodofraising
conditionsthatresultfromtheexecutionofstatement>s,themethodofaccessingthediagnostics
informationthatresultsfromtheexecutionofstatement>s,andthemethodofreturningtheresultsare
implementation-defined.
NoticethatDirectSQLis"implementationdefined,"hence
vendorshavewidediscretioninhowtheyimplementDirect
SQL.SQL*Plus®isanOracleimplementationofDirectSQL,as
isSQLServer'sQueryAnalyzer.Thesetoolsdifferinuser
interface;however,thesameSQLquerystatement,executed
acrossdifferenttools,willproducethesameresultset;thatis,
thesamedataandnumberofrowswillbethesame.
ThereexistsawidevarietyofSQLtoolsthatimplementdirect
SQL.ThesetoolsallowustotypebasicSQLstatementsand
executethemwithouttheadditionalcomplexityofacompileror
scriptinglanguage.SomeareGUIandsomeprovideabasic
commandlineinterface.ExamplesofsuchtoolsareSQL*Plus,
whichisbundledwiththeOracledatabasesoftware;SQL
Navigator®,whichislicensedbyQuestSoftware,SQL
WorksheetwhichisbundledwiththeOracleEnterpriseManager
(OEM)software;andTOAD,whichisalsoaQuestSoftware
product.Therearemanyothertoolsaswell.
ThereisaconceptualdifferencebetweenaccessingOracle,or
anyrelationaldatabase,throughacompilerlanguagesuchas
JavaandusingadirectquerytoollikeTOADorSQL*Plus.All
toolsthatimplementDirectSQLoperatewithinaninteractive


frameworksoyouneedtokeepthefollowingtwopointsin
mind.First,whenyouexecuteaquerywithSQL*Plus,orwith
anydirectSQLtool,theresultsaredumpedtoyourscreen.
Secondly,whenexecutingthesamequerywithinanapplication,
youmustdevelopcodetocapturetheresultsofyourquery.
ThisisillustratedwiththefollowingtwoSQLquerystatements.
ThefirstSQLstatementisaquerythatyouwouldexecutein
SQL*Plus.Uponexecutionofthestatement;thestudentname
isflushedtothescreen.

1.SELECTstudent_nameFROMregistered_studentsWHEREstudent_i
TheaforementionedSELECTstatementisavalidSQLstatement
forDirectSQLonly.ItwillnotcompileasanembeddedSQL
statementwithinacompiledprogram.TheSELECTstatement
embeddedinanapplicationprogramwillbeslightlydifferentthe
differenceistheadditionalINTOclause,shownnext.TheINTO
clausewillreferenceaprogramvariableintowhichthestudent
nameistobecopied.

[Viewfullwidth]

2.SELECTstudent_nameINTOmy_program_variableFROMregistered
='A101';
Therearevariationsontheaforementionedquerythatusethe
INTOclausewehaveexplicitcursors,cursorloops,andother
optionsthesetopicsarecoveredinChapter11.Itishelpfulto
keepinmindthatSQL*Plus,likeToadandotherdirectSQL
tools,isprimarilyaninteractivetoolyoudonotworryabout
capturingresultdata.Ontheotherhand,applicationprograms
docapturequeryresultdataandwhenyoudevelopcodeto
"capturedata"youhavedesignissues:multiplerowsreturned


exceptionconditionsthesetopicsareaddressedthroughoutthe
text.

1.2.4SQL*Plus
InadditiontobeinganimplementationofDirectSQL,SQL*Plus
isatrademarkednameforanOracleexecutableprogramthat
runsasacommandlineinteractiveprogram.Asmentionedin
Section1.2.3,therearemanySQLtoolsonecanusetoexecute
SQLagainstadatabase.We'vementionedSQL*Plus,Toad,SQL
Navigator,andSQLWorksheet.Infact,youcanuseSQLServer
SQLQueryAnalyzertorunyourqueriesagainstyourOracle
database.Youhavemanychoices.Thistextmakesuseof
SQL*Plus,butyou'llhavenodifficultyfollowingalongshould
youuseanothertoolforinteractingwithOracle.
SQL*Plusprimarilyservesanenduserinaclient/server
environment.Figure1-1illustratesacommonconfigurationthat
includesSQL*Plus.Inthisfigure,thecommunicationprotocol
acrossthisnetworkistheOracleNet8protocol.TheOracle
softwarethatrunsonyourclientsendstheSQLstatement
acrossthenetworktothedatabaseanditisOraclesoftware,on
thebackend,thatforwardsthedatabacktotheclient.Ifyou
runSQL*PlusandtypethefollowingSQLstatement:

SELECTstudent_nameFROMregistered_studentsWHEREstudent_id=

Figure1-1.SQL*PlusinaClient/ServerMode.


theSQLstatement,exactlyasyoutypeit,includingthesame
case,issentacrossinanetworkpackettotheOracleserver.
Theprocessedresult,thatbeingalistofstudentnames(inthis
caseprobablyjusttheonenameofthestudentwiththat
particularstudentID),isreturnedtotheSQL*Plusclientwhere
itisflushedtoyourscreen.
ThesendingandreceivingofdataisOracleNet8,whichis
OraclecommunicationsoftwareandrunsoverTCP/IP,orother
networkprotocols.SQL*PlusiswrittentoutilizeNet8,which
utilizesTCP/IPoverthenetwork.
SELECT,INSERT,UPDATE,andDELETEarethemostcommon
SQLstatementstheyarethecoremeansofmanipulatingdata.
Inadditiontothesecoredatamanipulationstatements,theSQL
standardincludesthespecificationforstatementslike:CREATE
DATABASE,ALTERDATABASE,CREATETABLE,CREATEVIEW,
CREATETRIGGER,andmanyotherSQLcommands.Anyvalid
SQLstatementcanbeexecutedfromSQL*Plus,includingthe
ALTERDATABASEstatement.So,allSQLstatements,notjust
thecommonINSERT,UPDATE,DELETE,SELECTcanbe
executedfromSQL*Plus.
TherearemanyadvantagestolearningSQL*Plus.Afeware
summarizedhere.
YouwillfindSQL*PlusintheOraclebindirectoryofevery
Oracleinstall.Ifyouinstallthedatabaseonanenterprise
server,youwillfindSQL*Plusinthebindirectory.Ifyou
installjusttheOracledevelopersoftwareonthedesktop,
youalsohaveSQL*Plus.Thisexecutableprogramisalways


there.So,intheabsenceofhavinganyothertools,youcan
alwaysbesureyouhavetheSQL*Plusprogram.
BecauseSQL*PlushasbeenavailablefromOraclethrough
somanyversions,theprogramhasanextremelywideuser
base.Itispopularforseveralreasons,oneofwhichisthe
factthatithasbeenaroundforsomanyyears.
SQL*Plusisasimplecommandlineinterfaceprogram.It's
notaGUIinterface;youdonothavemultiplescrollable
windowsthatshowtheSQLstatementinonewindowand
thequeryresultinanotherwindow.AlthoughGUIfeatures
havetheiradvantages,thesimplicityofSQL*Plusbecomes
advantageouswhenyouneedtobuildscripts.Youcanbuild
alibraryofSQL*Plusscripts,eachanASCIItextfile,and
thosescriptswillrunonOracleinUNIXoronOraclein
Windows.
SQL*Plushasallthefeaturesofapowerfulscripting
language.Itsupportsargumentpassing,commandfiles,
andnestedcommandfiles.Youcanhostouttoother
languages(e.g.,embedaWindowsscripthostfileorKorn
shellscriptwithinaSQL*Plusscript).SQL*Plusscriptscan
beincorporatedintootherscriptingprograms(i.e.,
SQL*PlusscriptscanbeembeddedinKornshellscripts;
illustratedinChapter2).Thesefeaturesmakethelanguage
highlyusefulfortoolbuilding.
Insummary,althoughSQL*Plusisanexcellenttooltofirst
experienceSQLandOracle,itisalsowidelyusedasa
developmentandadministrationtool.Peoplewhouse
SQL*PlusinitiallyuseittointroducethemselvestoOracle,
butyearslaterthey'restillusingitforapplications
developmentanddatabaseadministration.


1.3Tables
Databasetablesarethemostfundamentalstructureina
database.IfyouwereaskedtoworkonanewOracledatabase,
youwouldinitiallywonderhowmanytablesthereareinthe
application.Itmakesadifferencewhethertherearesixtables
or600tables,atleastintermsofhowmuchthereisforyouto
learnabouttheapplicationbeforeyoucanbeaproductive
developer.
Theexamplesinthistextarebasedonademostudentdata
model.Themodelstoresdataforstudents,courses,and
professors.Chapter4graphicallyillustratesthismodelincluding
theSQLcreatescripts.Akeytableinthismodelisthe
STUDENTStable.
AninitialplanforaSTUDENTStablerequiresansweringthe
question:"Whatattributesshouldbestoredforeachstudent?"
AninitialdraftofaSTUDENTStableincludestheseattributes:
Attribute

ColumnName

Auniquestudentnumber.Eachstudentisassignedanumberusedto
accessbillingandregistrationrecords.

STUDENT_ID

Astudentname.

STUDENT_NAME

AmajorfieldofstudysuchasScienceorHistory.

COLLEGE_MAJOR

Acollegeenrollmentstatusindicatingadegree-seekingorcertificateseekingstudent.

STATUS

Tableshavedifferentrepresentations.Originally,thetableisa
logicalentityconsistingofaboxonanentityrelationship
diagram.Inproduction,thetablecanbedescribedwiththe


SQL*PlusDescribecommandandrowscanbeselected.

1.3.1DataModelView
Thedatamodelviewofatableidentifiesthelogicalattributesof
theentitybeingstoredinthedatabase(Figure1-2).This
includesakeyattribute,whichistheprimarykey.Theprimary
keyisuniqueforeachinstanceoftheentity.Ifthetablestores
students,everystudentwillhaveauniqueprimarykey.The
datamodelviewisagraphicalrepresentation.

Figure1-2.StudentsTableinaDataModel.

1.3.2CreateTableScript
Oncethemodeliscompleteandallattributesaredefined,the
entitymustbecreatedinthedatabase.SQLisusedtocreatea
table.Thissteptransitionsthelogicalconcepttoaphysical


tableinthedatabase.WhenSQLcreatesobjects,suchas
tables,thisiscalledDataDefinitionLanguage(DDL).The
followingDDLcreatesaSTUDENTStableanddefinesthe
columntypeofeachattributetobeavariablelengthstringwith
amaximumsize.

CREATETABLEstudents
(student_idVARCHAR2(10),
student_nameVARCHAR2(30),
college_majorVARCHAR2(15),
statusVARCHAR2(15));

1.3.3DescribingtheTable
Thedefinitionofatablecaneasilybedescribedwiththe
SQL*Pluscommand.Thiscommandretrievesinformationfrom
thedatadictionaryinaformatthatconveystheinformation
storedinthetable.IftheDDLintheprevioussectionwereused
tocreatetheSTUDENTStable,theSQL*Plusdescribecommand
wouldreturnthefollowing:

SQL>descstudents
NameNull?Type
----------------------------------------------------STUDENT_IDNOTNULLVARCHAR2(10)
STUDENT_NAMENOTNULLVARCHAR2(30)
COLLEGE_MAJORNOTNULLVARCHAR2(15)
STATUSNOTNULLVARCHAR2(15)

1.3.4TableData


SQLstatementsthatmanipulaterowsinthetablearecalled
DataManipulationLanguage(DML).Oncethetableiscreated,
wecanaddstudentstothesystemwithINSERTstatements.

INSERTINTOstudents
VALUES('A101','John','Biology','Degree');
Akeycomponentofrelationaltechnology,emphasizedin
Section1.1,isthefreedomoftheprogrammertochoosewhat
datatoquery.Oncethetableiscreatedandrowsareinserted,
thereisnorestrictionwithdataaccess.Wecanqueryall
studentswithinaparticularmajor.Wecanqueryallstudents
whoaredegreecandidates.Wecanqueryalldegree-seeking
studentsmajoringineitherbiologyorhistory.

SELECTstudent_nameFROMstudentsWHEREcollege_major='Biolog
SELECTstudent_nameFROMstudentsWHEREstatus='Degree';

SELECTstudent_nameFROMstudentsWHERE
status='Degree'AND(college_major='Biology'ORcollege_major
Innetworkandhierarchicaldatabasetechnologies,the
programmercannot,atthelastminute,decidetoquerydatain
aparticularorder.Innetworkandhierarchicaldatabases,
orderedqueryresultsmustbebuiltintothedatabasestructure.
Inrelationaldatabaseswecan,asdevelopers,choosetoselect
studentsandtheirmajorinalphabeticalorder,reverse
alphabeticalorder,orderbyname,andorderbymajorwehave
norestriction.Theorderingofdataisnotinthedatabasebut
withintheSQLstatement.Sotopullallstudentnamesand
theirmajorinalphabeticalorder,weusetheORDERBYclause,
whichisacomponentoftheSQLspecification.Showingthis
orderedlist,weuse:


SELECTstudent_name,majorFROMstudentORDERBYstudent_name;
AllrowsofatablecanbeselectedwiththeSELECT*syntax.
ThefollowingistheSQL*Plussessionoutputthatselectsall
rowsfromthisSTUDENTStableafterfivestudentshavebeen
added.

SQL>SELECT*FROMstudents;
STUDENT_IDSTUDENT_NAMECOLLEGE_MAJORSTATUS
-------------------------------------------------A101JohnBiologyDegree
A102MaryMath/ScienceDegree
A103KathrynHistoryDegree
A104StevenBiologyDegree
A105WilliamEnglishDegree


1.4SQLStatements
TheSQLlanguageisprimarilyusedtocreatetablesand
manipulatetabledata;however,thelanguageincludes
statementsthatperformotherfunctions.SQLstatementsare
usedtocreatedatabaseaccounts,sizeandtunefor
performance,andperformadministrationtasks.AnOracle
databasefirstcomesintoexistencewithaSQLstatement,the
CREATEDATABASEstatement.Thefollowingdescribesthe
categoriesofSQLstatements.

1.4.1DataDefinitionLanguage(DDL)
CREATETABLEisaDDLstatement.DDLstatementsdefineour
databaseobjectsandresultinupdatestotheOracledata
dictionary.Theycreate,modify,anddeleteobjectssuchasa
tables,views,storedprocedures,databasetriggers,database
links,anddozensofotherobjectsinthedatabase.
DDLstatementscanalterexistingdatabaseobjectsincluding
tables.ColumnsandconstraintscanbeaddedwiththeALTER
TABLEcommand.Shouldwechoosetoaddacolumnfora
student'sagewecanexecutethefollowingSQLstatement,
whichaltersthedefinitionofthetableinthedatabasedata
dictionary.

ALTERTABLEstudentsADD(ageNUMBER(3));

1.4.2DataManipulationLanguage(DML)
DMLmanipulatesdatawiththefollowingstatements:


INSERT
UPDATE
DELETE
SELECT
SELECTstatementsdonotactuallymanipulatedata,butthe
SELECTstatementisoftenincludedwithintheconversational
contextof"DML."
AnOracledatabaseprovidestablechangesthroughINSERT,
UPDATE,andDELETEtocohabitatewithSELECTstatements.
TheconceptsupportedinanOracleenvironmentiscalled
consistentreadimage.Ausermakinguncommittedchangesto
thedatabasethroughINSERT,UPDATE,andDELETEstatements
doesnotblockauserwhoissuesaSELECTduringthatsame
timeframe.TransactionssuchasanINSERTthatarenot
committedtothedatabasedonotinterferewithconcurrent
SELECTstatementsagainstthesametables.ASELECT
statementisguaranteedaconsistentimage.Theresults
returnedtotheuserfromaSELECTstatementareguaranteed
tobefromthemostrecentconsistentimage,whichwillbethe
rowsasofthemostrecentCOMMIT.ACOMMITstatement
establishesanewcheckpointbywhichtabledataisupdatedto
aconsistentpointintime.

1.4.3TransactionControl
Transactioncontrolstatementsallowyoutobundleagroupof
DMLstatementsunderanall-or-nothingdomain.Thatis,"all
statementscompletesuccessfully,"orifonestatementfails,
thenallstatementsfailasonegroup.Examplesoftransaction


controlstatementsare:SETTRANSACTION,COMMIT,and
ROLLBACK.

1.4.4SessionControl
SessionControlstatementsaretemporaryandpersistforthe
durationoftheuser'sdatabaseconnection.AusefulSQLtuning
practiceistoturnSQLtraceonforthesession.Thisrecords
sessioninformationtoauserdumpdirectoryforSQLstatement
analysisusingtheOracletool,TKPROF.Thefollowingwillturn
tracingon/offforthesession.

ALTERSESSIONSETSQLTRACE[TRUE|FALSE]
OnceSQLTraceison,theuserrunstheapplication.During
executionOraclewritesdatatoatracefile.Thetracefilecanbe
analyzedusingtheOracleutility,TKPROF.Thefollowingshows
thehostcommandstringtoparsethetracefile.Theresultafter
runningTKPROFisanoutputASCIIfileshowingeachSQL
statementrunwithdetailtuninginformation.

tkproforacle_trace_file.trcoracle_output_trace_file.prf
explain=SCOTT/TIGER@ORAsys=no
Thefollowingisacommonaltersessioncommand.Italtersthe
defaultdisplayformatforcolumnswithaDATEtypetoinclude:
day,month,year,hours,minutes,andseconds.

ALTERSESSIONSETNLS_DATE_FORMAT='dd-mon-yyyyhh24:mi:ss';


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×

×