You are on page 1of 9

IntroductiontoDatabases

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

TAIF UNIVERSITY COLLEGE OF INFORMATION TECHNOLOGY

IntroductiontoDatabases
Employee
idEmployee name firstname address phone idDep

PreparedbySkanderTurki
Department
idDepartment department

2december2011

Assignment
idEmployee idProject

Project
idProject projectName description

PARTI:SimpleQueries QueryExamples: 1Firstqueries:PopulatetheDepartmenttablewithsomedata: >InsertIntoDepartment(idDepartment,department)Values(1,'HumanResources');


InsertIntoDepartment(idDepartment,department)Values(2,'Accounting'); InsertIntoDepartment(idDepartment,department)Values(3,'Marketing'); Select*fromDepartment;

Result: idDepartment department 1 2 3 HumanResources Accounting Marketing

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;

Result: idEmployee 1 Page name firstname addressphone idDep

RTYSalah AlAqiq 12345678NULL TAIF UNIVERSITY COLLEGE OF INFORMATION TECHNOLOGY

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.

4Usingmorethanatableinqueries:JOINqueries a Weneedtoknowforeachemployee,thenameofthedepatmentheworksin: Westartbyusingasimplecartesianjoinwithoutanyfiltering(nowhereclause):


Select*fromEmployeeAsT1,DepartmentAST2;

Page

TAIF UNIVERSITY COLLEGE OF INFORMATION TECHNOLOGY

IntroductiontoDatabases

PreparedbySkanderTurki

2december2011

Notethatthisresultisasimpleproductoftwotables.Eachlinedoesn'tnecessarilymean something.Tofilteronlythelinesthathaveameaningweaddtoourquerythewhere clausethatwillonlytakeintoaccounttherecordswhereidDep=idDepartment:


Select*fromEmployeeAsT1,DepartmentAST2 WhereT1.idDep=T2.idDepartment;

Result:

NowweusetheINNERJoin: >Select*fromEmployeeAsT1InnerjoinDepartmentAST2
onT1.idDep=T2.idDepartment;

Result:

UsingtheOuterJoin: Let'saddtwoemployeeswithoutassigningthemtoanydepartment:

InsertIntoEmployee(idEmployee,name,firstname,address,phone,idDep) Values(10,'TJIG','Mondhir','Makka','456786',NULL); InsertIntoEmployee(idEmployee,name,firstname,address,phone,idDep) Values(11,'FHTJ','Sabir','Riyadh','1354968',NULL);


Nowlet'saddadepartmentthatwillnothaveanyemployeeassignedtoit:

InsertIntoDepartment(idDepartment,department)Values(4,'Researchand Development');
Let'sseethedifferencebetweentheINNERandtheOUTERjoins:

Select*fromEmployeeAsT1InnerjoinDepartmentAST2 onT1.idDep=T2.idDepartment;

Page

TAIF UNIVERSITY COLLEGE OF INFORMATION TECHNOLOGY

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

TAIF UNIVERSITY COLLEGE OF INFORMATION TECHNOLOGY

IntroductiontoDatabases
Committransac onT1;

PreparedbySkanderTurki

2december2011

Thecommitkeywordwilllauchtheexecutionofthesequenceofqueries.WecanusetheRollbackkeywordtocancelallthe sequenceofqueries. NowbeforetestingthesefeaturesofSQL,weneedtoknowabouttheTRY/CATCHcontrolconstruct.Let'slookattheexample:

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;

Howthiscodewillbeexecuted?Firstnotethatyouhavetwomajorblocs: theBEGINTRYEndTRY:thisistheTRYbloc theBEGINCATCHEndCATCH:ThisistheCATCHbloc

ThismeansthatallthatisinsidetheTRYblocwillbeexecutedbutifanyerroroccursallthatisinside theCATCHblocwillbeexecuted.Solet'slookatourexamplehere:Wewillmakefiveconsecutive inser onsinonetransac onT1.Thatmeansthesefivequerieswillonlybeexecutedwhenthe committransactionisencountered.Butifanyerroroccurs,thentheCATCHblocwillbeexecutedand arollbackwilloccurcancellingallthetransaction. Let'stryittoseetheresultsofthepreviouscode.Let'sseethecontentoftheProjecttableby executingasimpleselect*:


select*fromproject

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

TAIF UNIVERSITY COLLEGE OF INFORMATION TECHNOLOGY

IntroductiontoDatabases
Wegetthesemessages:
(1row(s)affected) (0row(s)affected)

PreparedbySkanderTurki

2december2011

ThefirstmessagewastoinformusthatthefirstInsertwasexecutedcorrectly.Butwhentryingto executethesecondInsertanerrorwasraisedbecausewetryedtoinsertanotherprojectwithan idProjectequalto6.ThisexecutedtheCATCHBlocwhichrolledbacktheTransac onwhichgaveus thesecondmessageof0rowsaected.Notethatinthiscasethecommittransactionwasnot executed. Afterexecutingthiscode,wedon'thaveanyerrormessagebecauseitwascaughtbyourCATCHbloc. Butlet'sseethecontentoftheprojecttable:


select*fromproject

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...')

EndTRY BeginCATCH EndCATCH;

NotethatIremovedallthelinesthatwererelatedtothetransaction.Nowlet'sseethedatawehave:
select*fromproject

Page

TAIF UNIVERSITY COLLEGE OF INFORMATION TECHNOLOGY

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...')

EndTRY BeginCATCH EndCATCH;

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

TAIF UNIVERSITY COLLEGE OF INFORMATION TECHNOLOGY

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

TAIF UNIVERSITY COLLEGE OF INFORMATION TECHNOLOGY

You might also like