Tải bản đầy đủ (.pdf) (691 trang)

OReilly learning SQL on SQL server 2005 apr 2006 ISBN 0596102151

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (4.15 MB, 691 trang )

LearningSQLonSQLServer2005
BySikhaSahaBagui,RichardWalshEarp
...............................................
Publisher:O'Reilly
PubDate:April2006
PrintISBN-10:0-596-10215-1
PrintISBN-13:978-0-59-610215-9
Pages:342

TableofContents|Index

Anyonewhointeractswithtoday'smoderndatabasesneedstoknowSQL(Structured
QueryLanguage),thestandardlanguageforgenerating,manipulating,andretrieving
databaseinformation.Inrecentyears,thedramaticriseinthepopularityofrelational
databasesandmulti-userdatabaseshasfueledahealthydemandforapplication
developersandotherswhocanwriteSQLcodeefficientlyandcorrectly.

Ifyou'renewtodatabases,orneedaSQLrefresher,LearningSQLonSQLServer2005is
anidealstep-by-stepintroductiontothisdatabasequerytool,witheverythingyouneed
forprogrammingSQLusingMicrosoft'sSQLServer2005-oneofthemostpowerfuland
populardatabaseenginesusedtoday.Plentyofbooksexplaindatabasetheory.Thisguide
letsyouapplythetheoryasyoulearnSQL.Youdon'tneedpriordatabaseknowledge,or
evenpriorcomputerknowledge.

Basedonapopularuniversity-levelcoursedesignedbyauthorsSikhaSahaBaguiand
RichardWalshEarp,LearningSQLonSQLServer2005startswithverysimpleSQL
concepts,andslowlybuildsintomorecomplexquerydevelopment.Everytopic,concept,
andideacomeswithexamplesofcodeandoutput,alongwithexercisestohelpyougain
proficiencyinSQLandSQLServer2005.Withthisbook,you'lllearn:
BeginningSQLcommands,suchashowandwheretotypeanSQLquery,andhowto
create,populate,alteranddeletetables


HowtocustomizeSQLServer2005'ssettingsandaboutSQLServer2005'sfunctions
Aboutjoins,acommondatabasemechanismforcombiningtables
Querydevelopment,theuseofviewsandotherderivedstructures,andsimpleset
operations


Subqueries,aggregatefunctionsandcorrelatedsubqueries,aswellasindexesand
constraintsthatcanbeaddedtotablesinSQLServer2005

Whetheryou'reanundergraduatecomputerscienceorMISstudent,aself-learnerwhohas
accesstothenewMicrosoftdatabase,orworkforyourcompany'sITdepartment,Learning
SQLonSQLServer2005willgetyouuptospeedonSQLinnotime.


LearningSQLonSQLServer2005
BySikhaSahaBagui,RichardWalshEarp
...............................................
Publisher:O'Reilly
PubDate:April2006
PrintISBN-10:0-596-10215-1
PrintISBN-13:978-0-59-610215-9
Pages:342

TableofContents|Index















































LearningSQLonSQLServer2005
Dedication
Preface
WhyThisBook?
SQLandSQLServer
AudienceandCoverage
AFewNotesAboutSQLServer2005Installation
ConventionsUsedinThisBook
UsingCodeExamples
HowtoContactUs
Acknowledgments
Chapter1.StartingMicrosoftSQLServer2005
Section1.1.StartingMicrosoftSQLServer2005andSQLServer2005's
ManagementStudio
Section1.2.CreatingaDatabaseinMicrosoftSQLServer2005
Section1.3.TheQueryEditor
Section1.4.CreatingTablesUsingtheLoadScript
Section1.5.ViewingTableDefinitions
Section1.6.ModifyingTableDefinitions
Section1.7.ViewingTableData
Section1.8.DeletingaTable

Section1.9.DeletingaDatabase
Section1.10.EnteringaSQLQueryorStatement
Section1.11.ParsingaQuery

















































































Section1.12.ExecutingaQuery
Section1.13.SavingaQuery
Section1.14.DisplayingtheResults
Section1.15.StoppingExecutionofaLongQuery
Section1.16.PrintingtheQueryandResults
Section1.17.CustomizingSQLServer2005
Section1.18.Summary
Section1.19.ReviewQuestions

Section1.20.Exercises
Chapter2.BeginningSQLCommandsinSQLServer
Section2.1.DisplayingDatawiththeSELECTStatement
Section2.2.DisplayingorSELECTingRowsorTuplesfromaTable
Section2.3.TheCOUNTFunction
Section2.4.TheROWCOUNTFunction
Section2.5.UsingAliases
Section2.6.Synonyms
Section2.7.AddingCommentstoSQLStatements
Section2.8.SomeConventionsforWritingSQLStatements
Section2.9.AFewNotesAboutSQLServer2005Syntax
Section2.10.Summary
Section2.11.ReviewQuestions
Section2.12.Exercises
Chapter3.Creating,Populating,Altering,andDeletingTables
Section3.1.DataTypesinSQLServer2005
Section3.2.CreatingaTable
Section3.3.InsertingValuesintoaTable
Section3.4.TheUPDATECommand
Section3.5.TheALTERTABLECommand
Section3.6.TheDELETECommand
Section3.7.DeletingaTable
Section3.8.Summary
Section3.9.ReviewQuestions
Section3.10.Exercises
Section3.11.References
Chapter4.Joins
Section4.1.TheJOIN
Section4.2.TheCartesianProduct
Section4.3.Equi-JoinsandNon-Equi-Joins

Section4.4.SelfJoins














































































Section4.5.UsingORDERBYwithaJoin
Section4.6.JoiningMoreThanTwoTables
Section4.7.TheOUTERJOIN
Section4.8.Summary
Section4.9.ReviewQuestions
Section4.10.Exercises
Chapter5.Functions
Section5.1.AggregateFunctions
Section5.2.Row-LevelFunctions
Section5.3.OtherFunctions
Section5.4.StringFunctions
Section5.5.CONVERSIONFunctions
Section5.6.DATEFunctions

Section5.7.Summary
Section5.8.ReviewQuestions
Section5.9.Exercises
Chapter6.QueryDevelopmentandDerivedStructures
Section6.1.QueryDevelopment
Section6.2.ParenthesesinSQLExpressions
Section6.3.DerivedStructures
Section6.4.QueryDevelopmentwithDerivedStructures
Section6.5.Summary
Section6.6.ReviewQuestions
Section6.7.Exercises
Chapter7.SetOperations
Section7.1.IntroducingSetOperations
Section7.2.TheUNIONOperation
Section7.3.TheUNIONALLOperation
Section7.4.HandlingUNIONandUNIONALLSituationswithanUnequal
NumberofColumns
Section7.5.TheINandNOT..INPredicates
Section7.6.TheDifferenceOperation
Section7.7.TheUnionandtheJoin
Section7.8.AUNIONUsedtoImplementaFullOuterJoin
Section7.9.Summary
Section7.10.ReviewQuestions
Section7.11.Exercises
Section7.12.OptionalExercise
Chapter8.JoinsVersusSubqueries












































































Section8.1.SubquerywithanINPredicate
Section8.2.TheSubqueryasaJoin
Section8.3.WhentheJoinCannotBeTurnedintoaSubquery
Section8.4.MoreExamplesInvolvingJoinsandIN
Section8.5.UsingSubquerieswithOperators
Section8.6.Summary
Section8.7.ReviewQuestions
Section8.8.Exercises
Chapter9.AggregationandGROUPBY
Section9.1.ASELECTinModifiedBNF
Section9.2.TheGROUPBYClause
Section9.3.TheHAVINGClause
Section9.4.GROUPBYandHAVING:AggregatesofAggregates
Section9.5.AuditinginSubqueries
Section9.6.NullsRevisited
Section9.7.Summary
Section9.8.ReviewQuestions
Section9.9.Exercises
Chapter10.CorrelatedSubqueries
Section10.1.NoncorrelatedSubqueries
Section10.2.CorrelatedSubqueries

Section10.3.ExistenceQueriesandCorrelation
Section10.4.SQLUniversalandExistentialQualifiers
Section10.5.Summary
Section10.6.ReviewQuestions
Section10.7.Exercises
Chapter11.IndexesandConstraintsonTables
Section11.1.The"Simple"CREATETABLE
Section11.2.Indexes
Section11.3.Constraints
Section11.4.Summary
Section11.5.ReviewQuestions
Section11.6.Exercises
AppendixA.TheStudentDatabaseandOtherTablesUsedinThisBook
SectionA.1.
AppendixB.ScriptUsedtoCreatetheStudent_courseDatabase
GlossaryofTerms
ImportantCommandsandFunctions
AbouttheAuthor




Colophon



Index


LearningSQLonSQLServer2005

LearningSQLonSQLServer2005
bySikhaSahaBaguiandRichardWalshEarp
Copyright©2006O'ReillyMedia,Inc.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles(safari.oreilly.com).Formoreinformation,contact
ourcorporate/institutionalsalesdepartment:(800)998-9938or

Editor:

JeffPepper

ProductionEditor:

PhilipDangler

Copyeditor:

NancyWolfeKotary

Indexer:

JohnnaVanHooseDinse

CoverDesigner:

KarenMontgomery


InteriorDesigner:

DavidFutato

CoverIllustration:

DoverPictoralArchive

Illustrators:

RobertRomanoandJessamynRead


PrintingHistory:



April2006:

FirstEdition.

NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
LearningSQLonSQLServer2005,theimageofaribbednewt,
andrelatedtradedressaretrademarksofO'ReillyMedia,Inc.
AdaptedwithpermissionfromLearningSQL:Step-by-StepGD
UsingOraclebyBaguiandEarp,pp.48-61,69-70,85,89-93,
105-108,109-110,114-120,122-129,131-133,135-152,153166,167-183,185-213,Appendix3,andGlossaryofTerms,©
2003PearsonEducation,Inc.Reprintedbypermissionof

PearsonEducation,Inc.,PublishingasPearsonAddison-Wesley.
Allrightsreserved.
Adaptatedwithpermissionfrom,LearningSQL:Step-by-Step
GDUsingAccessbyBaguiandEarp,pp.64-77,©2003
PearsonEducation,Inc.ReproducedbypermissionofPearson
Education,Inc.PublishingasPearsonAddisonWesley.Allrights
reserved.
Oracle®andallOracle-basedtrademarksandlogosare
trademarksorregisteredtrademarksofOracleCorporation,Inc.
intheUnitedStatesandothercountries.O'ReillyMedia,Inc.is
independentofOracleCorporation.
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen


printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorsassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.
ISBN:0-596-10215-1
[M]




Dedication
Dedicatedtomyfather,SantoshSaha,andmother,

RanuSaha
and
myhusband,SubhashBagui
and
mysons,SumonandSudip
and
Pradeep,Priyashi,andPiyaliSaha
S.B.

Tomywife,Brenda,
and
mychildren:Beryl,Rich,Gen,andMaryJo
R.E.




Preface
SQLServerisoneofthemostpowerfuldatabaseenginesused
today.Microsoft'slatestreleaseofSQLServer,SQLServer
2005,isacomprehensivedatabaseplatformthatprovides
secureandreliablestorageforbothrelationalandstructured
data,enablingonetobuildandmanagehigh-performancedata
applications.SQLServer2005'scloseintegrationwithMicrosoft
VisualStudio,theMicrosoftOfficeSystem,andasuiteofnew
developmenttoolssetSQLServer2005apartfromprevious
versionsandfromotherdatabaseengines.Thissystemallows
developerstobuild,debug,andoperateapplicationsfasterthen
everbefore.
SQLServer2005canbeinstalledonsmallmachinesusing

MicrosoftWindowsaswellasonlargeservers.Inrecentyears,
thecomputerindustryhasseenadramaticincreaseinthe
popularityofrelationaldatabasesandmultiuserdatabases,and
thecomputerindustryneedsapplicationdevelopersandpeople
whocanwriteSQLcodeefficientlyandcorrectlyforrelational
andmultiuserdatabases.




WhyThisBook?
Thisbookismainlyintendedtobeasystematicguideto
learningSQLusingSQLServer2005--arelationalandmultiuser
database.ThebookisaimedatstudentswhowishtolearnSQL
usingMicrosoft'sSQLServer2005.Thebookisexpectedtobe
usedbyschoolsandSQLtrainingorganizationsaswellasby
databaseandITprofessionalswhoareactivelyworkingwith
SQLServer2005.
ThebookstartswithverysimpleSQLconcepts,andslowly
buildsintomorecomplexquerydevelopment.Thepurposeof
thisbookistopresenteverytopic,concept,andideawith
examplesofcodeandoutput.Exerciseshavealsobeenincluded
togainSQLproficiencyusingSQLServer.Thebestapproachto
usingthisbookefficientlyistoreadthroughthebookwithSQL
Serveropenandactive.Asthebookisread,itwillbe
advantageousforyoutoworkwithandunderstandthe
examples.
Ifthebookisusedforabeginningdatabasecourse,the
exercisesarepresentedtobedonebythestudentsoverthe
courseofonesemesteratapaceofonechapterperweek.The

exercisesarefoundattheendofeachchapter.
Duetothedramaticincreaseinthepopularityofrelationaland
multiuserdatabases,manyschoolsandtrainingorganizations
areusingSQLServerintheirdatabasecoursestoteach
databaseprinciplesandconcepts.Thisdevelopmenthas
generatedaneedforaconcisebookonSQLServer
programming,tiedinwithdatabaseprinciplesand
conceptshencethisbook.




SQLandSQLServer
SQL(StructuredQueryLanguage)isastandardlanguageused
forquerying,updating,andmanagingrelationaldatabases,and
latelySQLhasbecomethedefactostandard"language"for
accessingrelationaldatabases.SQLisnotreallyasmuchofa
languageasitisadatabasequerytool.Inthisbook,we
concentrateonlearningSQLusingSQLServer2005.
SQLallowsustodefinearelationaldatabasecreateandmodify
tables(inthissense,SQLisadatadefinitionlanguage,orDDL).
SQLalsoallowsustotellSQLServerwhichinformationwe
wanttoselect(retrieve),insert,update,ordelete.Thatis,SQL
alsoallowsustoquerytherelationaldatabaseinamostflexible
way,aswellastochangethestoreddata(andinthissense,
SQLisadatamanipulationlanguage,orDML).
ThebookistargetedatSQLServerusersontheWindows
operatingsystem,butiseasilyadaptabletootherplatforms.



AudienceandCoverage
Abooklikethiscanbeusedinan"IntroductiontoDatabases"
courseoraseconddatabasecoursealongwithtextbookslike
FundamentalsofDatabaseSystems,4thEdition,Addison
Wesley,2003(ElmasriandNavathe),andDatabaseProcessing,
Fundamentals,Design&Implementation,9thEdition,Prentice
Hall,2003(DavidKroenke).Studentscouldlearnthedatabase
theoryfromthetexts,andapplythetheoryusingthisbook
(usingSQLServer)astheylearnSQL.
Thisbookcanalsobeusedasastandalonetextinacourseon
learningSQLusingSQLServer2005.Thisbookdoesnot
assumeanypriorcomputerknowledge.
Thisbookconsistsof11chapters.Chapter1introducesthe
usertoSQLServer2005.InChapter1,youwilllearnhowto
openSQLServer2005usingSQLServerManagementStudio,
loadthedatabase,andviewandperformsimpletable
manipulations.Chapter1alsointroducestheusertothequery
editor;showsyouhowtoview,save,andprintqueriesand
output;andhowtocustomizeSQLServer2005'ssettings.
Chapter2introducestheuser/learnertosomebasicSQL
commandsinSQLServer.Chapter3discussescreating,
populating,altering,anddeletingtables;anexamplerelational
databaseisbuiltontheideaoftabulardata.Chapter4
introducesandcoversdifferenttypesofjoinsacommon
databasemechanismforcombiningtables.Chapter5covers
SQLServer2005'sfunctions.Chapter6discussesquery
developmentaswellastheuseofviewsandotherderived
structures.Chapter7coverssimplesetoperations.Chapters8,
9,and10coversubqueries,aggregatefunctions,andcorrelated
subqueries;andChapter11presentsindexesandconstraints

thatcanbeaddedtotablesinSQLServer2005.
AppendixAdescribestheStudent_coursedatabaseandother


databasesthathavebeenusedthroughoutthebook.Appendix
BprovidestheactualscriptusedtocreatetheStudent_course
database.Glossariesdefiningtermsandimportantfunctionsare
provided,aswellasindexesoftermsandfunctionsinthebook.
ThebookissufficientforbeginningSQLuserstogetan
overviewofwhatSQLServerentailsandhowtouseSQL.Many
SQLprogrammershavebasedtheiremploymentonthis
material.ThebookgivesaverygoodfeelforwhatSQLis,and
howSQLisusedinSQLServer.




AFewNotesAboutSQLServer2005Installation
Forbestresults,oneshouldinstallSQLServer2005ona
computerthatdoesnothaveaprereleaseversionofSQLServer
2005,VisualStudio2005,orthe.NETFramework2.0installed
onit.Ifyourcomputerhasanyoftheprereleaseversionsonit,
theymustberemovedinthecorrectorderbeforeyoucan
successfullymanuallyinstalltheactualversionofSQLServer
2005software.Forthecorrectorderoftheserequired
uninstallationsbeforeyoucaninstallSQLServer2005,visit:

/>Westronglyrecommendthatyouinsteadruntheautoinstall
tool(foundatthesamesite),ratherthanattemptingamanual
install.

Oncetheuninstallhasbeencorrectlydone,youmay
successfullyloadSQLServer2005andbeginlearningSQL.


ConventionsUsedinThisBook
Thefollowingconventionsareusedinthisbook:

Italic
UsedforURLsandforemphasiswhenintroducinganew
term.

Constantwidth
UsedforMySQLandSQLkeywordsandforcodeexamples.

Constantwidthbold
Insomecodeexamples,highlightsthestatementsbeing
discussed.

Constantwidthitalic

Insomecodeexamples,indicatesanelement(e.g.,a
filename)thatyousupply.

UPPERCASE
Incodeexamples,generallyindicatesMySQLkeywords.


lowercase
Incodeexamples,generallyindicatesuser-defineditems
suchasvariables,parameters,etc.


punctuation
Incodeexamples,enterexactlyasshown.

indentation
Incodeexamples,helpstoshowstructurebutisnot
required.

-Incodeexamples,beginsasingle-linecommentthat
extendstotheendofaline.

/*and*/
Incodeexamples,delimitamultilinecommentthatcan
extendfromonelinetoanother.

.
Incodeexamplesandrelateddiscussions,qualifiesa
referencebyseparatinganobjectnamefromacomponent
name.


[]
Insyntaxdescriptions,encloseoptionalitems.

{}
Insyntaxdescriptions,encloseasetofitemsfromwhich
youmustchooseonlyone.

|
Insyntaxdescriptions,separatestheitemsenclosedin

curlybrackets,asin{TRUE|FALSE}.

...
Insyntaxdescriptions,indicatesrepeatingelements.An
ellipsisalsoshowsthatstatementsorclausesirrelevantto
thediscussionwereleftout.

Indicatesatip,suggestion,orgeneralnote.Forexample,we'lltellyou
ifacertainsettingisversion-specific.

Indicatesawarningorcaution.Forexample,we'lltellyouifacertain
settinghassomekindofnegativeimpactonthesystem.





UsingCodeExamples
Thisbookisheretohelpyougetyourjobdone.Ingeneral,you
mayusethecodeinthisbookinyourprogramsand
documentation.Youdonotneedtocontactusforpermission
unlessyou'rereproducingasignificantportionofthecode.For
example,writingaprogramthatusesseveralchunksofcode
fromthisbookdoesnotrequirepermission.Sellingor
distributingaCD-ROMofexamplesfromO'Reillybooksdoes
requirepermission.Answeringaquestionbycitingthisbook
andquotingexamplecodedoesnotrequirepermission.
Incorporatingasignificantamountofexamplecodefromthis
bookintoyourproduct'sdocumentationdoesrequire
permission.

Weappreciate,butdonotrequire,attribution.Anattribution
usuallyincludesthetitle,author,publisher,andISBN.For
example:"LearningSQLonSQLServer2005bySikhaSaha
BaguiandRichardWalshEarp.Copyright2006O'ReillyMedia,
Inc.,0-596-10215-1."
Ifyoufeelthatyouruseofcodeexamplesfallsoutsidefairuse
orthepermissiongivenhere,feelfreetocontactusat



HowtoContactUs
Wehavetestedandverifiedtheinformationinthisbookandin
thesourcecodetothebestofourability,butgiventheamount
oftextandtherapidevolutionoftechnology,youmayfindthat
featureshavechangedorthatwehavemademistakes.Ifso,
pleasenotifyusbywritingto:
O'ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
800-998-9938(intheUnitedStatesorCanada)
707-829-0515(internationalorlocal)
707-829-0104(fax)
Youcanalsosendmessageselectronically.Tobeputonthe
mailinglistorrequestacatalog,sendemailto:

Toasktechnicalquestionsorcommentonthebook,sendemail
to:

Asmentionedintheearliersection,wehaveawebsiteforthis
bookwhereyoucanfindcode,errata(previouslyreported

errorsandcorrectionsavailableforpublicview),andotherbook
information.Youcanaccessthiswebsiteat:
/>Formoreinformationaboutthisbookandothers,seethe
O'Reillywebsite:



Acknowledgments
Ourspecialthanksareduetooureditor,JeffPepper,andthe
productioncrewatO'Reillyforputtingupwithallthechanges.
WewouldalsoliketothankPresidentJohnCavanaugh,Dean
JaneHalonen,andProvostSandraFlakeoftheUniversityof
WestFloridafortheirinspiration,encouragement,support,and
trueleadershipquality.Wewouldalsoliketoexpressour
gratitudetoDr.WesLittleonthesameendeavor.
OursincerethanksalsogotoDr.EdRodgersforhiscontinuing
supportandencouragementthroughoutpastyears.Wealso
appreciateDr.LeoTerhaar,chair,ComputerScience
Department,forhisadvice,guidance,andsupport,and
encouragingustocompletethisbook.Last,butnotleast,we
wouldliketothankourfellowfacultymembers,Dr.JimBezdek
andDr.NormanWildefortheircontinuoussupportand
encouragement.




Chapter1.StartingMicrosoftSQLServer
2005
ThischapterintroducesSQLServer2005andSQLServer

2005'sManagementStudioanditsbasicworkings.Youwill
learnhowtocreateadatabase,viewtheobjectsanddefault
tablesinadatabase,useaqueryeditor,activatethedatabase
indifferentways,andcreatetablesinthedatabaseusingaload
script.Theloadscriptisavailableat
Theloadscriptwillcreatethe
Student_coursedatabaseforyou.Thisdatabasewillbeused
throughouttherestofthebooktolearnSQL.Atthispoint,you
maywanttocopytheloadscript,SQLServer2005_load.sql,to
yourworkingdirectoryonyourcomputer,beforeyoustart
workingonthenextsection.Right-clickonthescriptonthe
website,selectSaveTargetAs,andsaveittoyourworking
directory.
Inthischapter,youwillalsolearnhowtoviewandmodifytable
definitions;deleteatableandadatabase;type,parse,execute
andsaveaquery;displaytheresultsindifferentforms;stop
executionofaquery;andprintthequeryandresults.Thefinal
sectionofthischapterdiscussescustomizingSQLServer2005's
settings.


×