SQL Server Tutorial PDF
SQL Server Tutorial PDF
PreparedbySkanderTurki
2december2011
SQLServerDatabasesTutorial
Introduction: Thistutorialwillhelpthestudentsapplythetheorytheylearninthelecturesusingoneof themostspreadRDBMSwhichisMicroso 'sSQLServer.I'musingthe2012RC0versionof SQLServer. Prerequisites: YouneedtoinstallSQLServer2012Expressedi onwhichisthedatabaseengine(Themost importantpart)andalsoSQLservermanagementstudiowhichisthegraphicalinterfacethat facilitatesthedatabasecreationandquerydevelopmentandexecution.Theyareavailable undertheselinks: Underthislinkyouhavetoselect"expresswithtools"fromthe"selectaproduct"drop downlistanddownloadit.Thengotosamelinkandthistimechoose"SQLServer managementstudio"anddownloadit. http://www.microso .com/betaexperience/pd/SQLEXPCTAV2/enus/default.aspx Installbothpackages.Noticethatyouneedtogiveanametoyourserver,chooseanyone wordnameandchoosewindowsauthentificationsothatyouwillnotneedtochoosea password,whenyouareconnectedtowindows,sqlserverconsidersyouaretherightuser. Thismakesthingsmuchsimplerforthebeginner. HumanResourcesDatabase: CreatingthedatabaseisquitestraightforwardusingtheSQLServermanagementstudio.In theleftpanerightclickondatabasesthenclickon"newdatabase".Thenclickonthenew databaseyoujustcreatedthenrightclickon"tables"anclickon"newtable".Thendefine theEmployeetableaccordingtothediagrambelow.Thendothesamethingforeachtable. Todefineaprimarykey,youneedtoselectthefieldandclickontheyellowkeybuttonthat isontheupperleftofthetoolbox.Ifakeyiscomposedofmorethanonefieldselectallthe fieldstogether(byholdingthecntlkeypushed)thenclickontheyellowkey. Nowyouneedtocreaterelationshipsbetweeneachprimarykeywithitscorresponding foreignkey.Todothat,thesimplestwayistocreateadiagram.Sorightclickondatabase diagramsthen"newdatabasediagram".Whenitopensrightclickonthemiddleofthe emptydiagramandclickon"addtable".Selectallthetablesyoucreated,theywillbeadded insidethediagram.NowdraganddroptheidDepartmentfieldfromtheDepartmenttable ontheidDepfieldintheEmployeetable,thiswillcreatethelink.Dothesamethingwiththe otherrelationships.
Page
IntroductiontoDatabases
Employee
idEmployee name firstname address phone idDep
PreparedbySkanderTurki
Department
idDepartment department
2december2011
Assignment
idEmployee idProject
Project
idProject projectName description
2Secondqueries:PopulatetheEmployeetablewithsomedata:
InsertIntoEmployee(idEmployee,name,firstname,address,phone,idDep) Values(1,'RTY','Salah','AlAqiq','12345678',NULL); InsertIntoEmployee(idEmployee,name,firstname,address,phone,idDep) Values(2,'UIO','Mounir','AlHawiyya','2548789',NULL); InsertIntoEmployee(idEmployee,name,firstname,address,phone,idDep) Values(3,'FDG','Qassim','AlTaif','4523698',NULL); InsertIntoEmployee(idEmployee,name,firstname,address,phone,idDep) Values(4,'SDQ','Hafidh','AlAziziyya','9874632',NULL); Select*fromEmployee;
IntroductiontoDatabases 2 3 4
PreparedbySkanderTurki
2december2011
UIOMounir AlHawiyya2548789 NULL FDGQassim AlTaif 4523698 NULL SDQHafidh AlAziziyya9874632 NULL
3Updateemployeeswiththedepartmentnumber:
UpdateEmployeeSetidDep=3whereidEmployee=1; UpdateEmployeeSetidDep=1whereidEmployee=2; UpdateEmployeeSetidDep=2whereidEmployee=3; UpdateEmployeeSetidDep=3whereidEmployee=4; Select*fromemployee;
Result:
idEmployee 1 2 3 4 name firstname address phone idDep RTYSalahAlAqiq 123456783 UIOMounirAlHawiyya25487891 FDGQassimAlTaif 4523698 2 SDQHafidhAlAziziyya98746323
4Selectqueries: a Whoaretheemployeeswhichfirstnamescontainan'a'?
Select*fromEmployeewherefirstnameLIKE'%a%'; Result:
idEmployee 1 3 4
name firstname addressphoneidDep RTY Salah AlAqiq 12345678 3 FDG Qassim AlTaif 4523698 2 SDQ Hafidh AlAziziyya9874632 3
b Whichemployeeshaveanamethatstartswitha'Q'andcontainsan's'inthethird position?
Select*fromEmployeewherefirstnameLIKE'Q_s%'; Result: idEmployee name firstname addressphone idDep 3 FDGQassimAlTaif4523698 2
c Whichemployeeslivein'AlHawiyya'?
Select*fromEmployeewhereaddressLIKE'%AlHawiyya%'; Or Select*fromEmployeewhereaddressLIKE'%AlHAwiYYA%'; Result: idEmployee name firstname address phone idDep 2 UIOMounirAlHawiyya 25487892 NoticethatinSQLServerusingupperorlowercasecharactersdoesn't makeadifference.
Page
IntroductiontoDatabases
PreparedbySkanderTurki
2december2011
Result:
NowweusetheINNERJoin: >Select*fromEmployeeAsT1InnerjoinDepartmentAST2
onT1.idDep=T2.idDepartment;
Result:
UsingtheOuterJoin: Let'saddtwoemployeeswithoutassigningthemtoanydepartment:
InsertIntoDepartment(idDepartment,department)Values(4,'Researchand Development');
Let'sseethedifferencebetweentheINNERandtheOUTERjoins:
Select*fromEmployeeAsT1InnerjoinDepartmentAST2 onT1.idDep=T2.idDepartment;
Page
IntroductiontoDatabases
PreparedbySkanderTurki
2december2011
Ifweusealeftouterjoin:
Select*fromEmployeeAsT1LeftOuterjoinDepartmentAST2 onT1.idDep=T2.idDepartment;
Nowarightouterjoin:
Select*fromEmployeeAsT1RightOuterjoinDepartmentAST2 onT1.idDep=T2.idDepartment;
AndnowaFullOuterJoin:
Select*fromEmployeeAsT1FullouterjoinDepartmentAST2 onT1.idDep=T2.idDepartment;
PARTII:Transactions
Nowwewillseehowwecanexecuteagroupofqueriesinanatomicway:Whichmeansallthegroupofquerieswilleitherbe completelyexecutedorcompletelycanceled.Allthequeriesinsidethegroupwillbeexecutedwithoutbeinginterruptedbyany otherqueryexternaltothatgroup.Inotherwords,thestateofthedatabasebetweentheexecutionoftwosuccessivequeries ofthatgroupwillnotbeaccessibletoanyone.Thisgroupofqueriesiscalledatransaction.Thesyntaxofthetransactionisas follows: Begintransac onT1 Query_1 Query_n
Page
IntroductiontoDatabases
Committransac onT1;
PreparedbySkanderTurki
2december2011
BeginTRY BeginTransactionT1
InsertintoProject(idProject,projectName,description)Values(1,'DTRG','thisprojwill...') InsertintoProject(idProject,projectName,description)Values(2,'JGHT','thisprojwill...') InsertintoProject(idProject,projectName,description)Values(3,'ERTY','thisprojwill...') InsertintoProject(idProject,projectName,description)Values(4,'VBNH','thisprojwill...') InsertintoProject(idProject,projectName,description)Values(5,'OPQS','thisprojwill...') CommitTransactionT1;
EndTRY BeginCATCH
RollbackTransactionT1;
EndCATCH;
Nowwewillforcethepreviouscodetomakeanerrorbytryingtoinserttwoprojectswiththesame idProject,thisshouldraiseanerrorbecausetheidProjectisaprimarykey.Hereisthemodifiedcode:
BeginTRY BeginTransactionT1
InsertintoProject(idProject,projectName,description)Values(6,'FTHK','thisprojwill...') InsertintoProject(idProject,projectName,description)Values(6,'MLPO','thisprojwill...') CommitTransactionT1;
EndTRY BeginCATCH
RollbackTransactionT1;
EndCATCH;
Page
IntroductiontoDatabases
Wegetthesemessages:
(1row(s)affected) (0row(s)affected)
PreparedbySkanderTurki
2december2011
Nowlet'scomparethesamecodewithouttheBegintransactionCommitRollbacklinesofcode: Firstlet'sdeleteallthedatafromtheprojecttable:
deletefromproject
Thisemptiesthetable,youcanverifythatbythesimpleselect* Nowlet'sexecutethiscode:
BeginTRY
InsertintoProject(idProject,projectName,description)Values(1,'DTRG','thisprojwill...') InsertintoProject(idProject,projectName,description)Values(2,'JGHT','thisprojwill...') InsertintoProject(idProject,projectName,description)Values(3,'ERTY','thisprojwill...') InsertintoProject(idProject,projectName,description)Values(4,'VBNH','thisprojwill...') InsertintoProject(idProject,projectName,description)Values(5,'OPQS','thisprojwill...')
NotethatIremovedallthelinesthatwererelatedtothetransaction.Nowlet'sseethedatawehave:
select*fromproject
Page
IntroductiontoDatabases
PreparedbySkanderTurki
2december2011
OK,nowwewilltrythesamethingaspreviously;Inser ngtwoprojectwithidProject=6:
BeginTRY
InsertintoProject(idProject,projectName,description)Values(6,'MLOP','thisprojwill...') InsertintoProject(idProject,projectName,description)Values(6,'ZSAQ','thisprojwill...')
Wegetthesemessages:
(1row(s)affected) (0row(s)affected)
Butlet'slookatthedatawenowhaveinourtable:
select*fromproject
WecanseethatthefirstprojectwithidProjectwasinserted.Thatwastherstmessage"1row added".Thesecondmessage"0rowadded"wastheanswertooursecondinsertthatdidn'twork. Conclusion: Sonow,whatisthedifferencebetweenthefirstapproach(usingtransactions)andthesecond? Whenwehadanerrorinthefirstexample,theCatchblocrolledbackalltheinsertions.That'swhywe didn'thaveanyinsertionexecuted.Butinthesecondexample(withouttransactions),eachinsertion isexecutedoneaftertheotheranddataisinsertedinthedatabasedirectly.That'swhythefirstquery executednormallyandthesecondquerydidn'thaveanyeffectontheexecutionofthefirstoneeven ifitraisedanerror. Theuseoftransactionsisusedonlywhenwewanttomakesurethateitheralltheoperationsare doneortheymustallbecancelledifanyundesirablesituationoccurs.
Page
IntroductiontoDatabases
PreparedbySkanderTurki
2december2011
PARTIII:DatabasecreationandmodificationthroughSQLDDL
Nowlet'strysomeDDLcommands.Wewillcreateanewtablewithaprimarykeyandaforeignkey relatedtoEmployee.idEmployee:
UsehumanRessources createtabletrial(idintegerprimarykeynotnull,empbigintforeignkey referencesEmployee(idEmployee)notnull) Let'sconsultthenewtable:select*fromtrial
Ok,thetableistherebutithasnodatawhichisnormal;wejustcreatedit. Nowi'llsimplydestroyit:droptabletrial
Command(s)completedsuccessfully.
Nowlet'sreexecutetheselect:select*fromtrial
Msg208,Level16,State1,Line1 Invalidobjectname'trial'. Wegotanerrormessagetellingusthereisnosuchtablecalled'trial',ithas beenremovedcompletelyfromourdatabase.Notethatthisactionisverydangerous asitcandestroyanytablewithallthedataitcontainsinjustthreewords.
ToBeContinuedInchallah..
Page