0% found this document useful (0 votes)
168 views9 pages

SQL Server Tutorial PDF

This document provides an introduction and overview of SQL Server databases and basic queries. It discusses installing SQL Server 2012 Express and SQL Server Management Studio. It describes creating sample tables for a human resources database with employees, departments, projects, and assignments. The document then provides examples of simple queries, JOIN queries, and transactions in SQL Server.

Uploaded by

KRAZA2092
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
168 views9 pages

SQL Server Tutorial PDF

This document provides an introduction and overview of SQL Server databases and basic queries. It discusses installing SQL Server 2012 Express and SQL Server Management Studio. It describes creating sample tables for a human resources database with employees, departments, projects, and assignments. The document then provides examples of simple queries, JOIN queries, and transactions in SQL Server.

Uploaded by

KRAZA2092
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

IntroductiontoDatabases

PreparedbySkanderTurki

2december2011

SQLServerDatabasesTutorial
Introduction: Thistutorialwillhelpthestudentsapplythetheorytheylearninthelecturesusingoneof themostspreadRDBMSwhichisMicroso 'sSQLServer.I'musingthe2012RC0versionof SQLServer. Prerequisites: YouneedtoinstallSQLServer2012Expressedi onwhichisthedatabaseengine(Themost importantpart)andalsoSQLservermanagementstudiowhichisthegraphicalinterfacethat [Link] undertheselinks: Underthislinkyouhavetoselect"expresswithtools"fromthe"selectaproduct"drop [Link]"SQLServer managementstudio"anddownloadit. [Link] .com/betaexperience/pd/SQLEXPCTAV2/enus/[Link] [Link],chooseanyone wordnameandchoosewindowsauthentificationsothatyouwillnotneedtochoosea password,whenyouareconnectedtowindows,sqlserverconsidersyouaretherightuser. Thismakesthingsmuchsimplerforthebeginner. HumanResourcesDatabase: [Link] theleftpanerightclickondatabasesthenclickon"newdatabase".Thenclickonthenew databaseyoujustcreatedthenrightclickon"tables"anclickon"newtable".Thendefine [Link]. Todefineaprimarykey,youneedtoselectthefieldandclickontheyellowkeybuttonthat [Link] fieldstogether(byholdingthecntlkeypushed)thenclickontheyellowkey. Nowyouneedtocreaterelationshipsbetweeneachprimarykeywithitscorresponding [Link],[Link] diagramsthen"newdatabasediagram".Whenitopensrightclickonthemiddleofthe emptydiagramandclickon"addtable".Selectallthetablesyoucreated,theywillbeadded [Link] ontheidDepfieldintheEmployeetable,[Link] 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

[Link]'tnecessarilymean [Link] clausethatwillonlytakeintoaccounttherecordswhereidDep=idDepartment:


Select*fromEmployeeAsT1,DepartmentAST2 [Link]=[Link];

Result:

NowweusetheINNERJoin: >Select*fromEmployeeAsT1InnerjoinDepartmentAST2
[Link]=[Link];

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 [Link]=[Link];

Page

TAIF UNIVERSITY COLLEGE OF INFORMATION TECHNOLOGY

IntroductiontoDatabases

PreparedbySkanderTurki

2december2011

Ifweusealeftouterjoin:

Select*fromEmployeeAsT1LeftOuterjoinDepartmentAST2 [Link]=[Link];

Nowarightouterjoin:

Select*fromEmployeeAsT1RightOuterjoinDepartmentAST2 [Link]=[Link];

AndnowaFullOuterJoin:

Select*fromEmployeeAsT1FullouterjoinDepartmentAST2 [Link]=[Link];

PARTII:Transactions
Nowwewillseehowwecanexecuteagroupofqueriesinanatomicway:Whichmeansallthegroupofquerieswilleitherbe [Link] [Link],thestateofthedatabasebetweentheexecutionoftwosuccessivequeries [Link] follows: Begintransac onT1 Query_1 Query_n

Page

TAIF UNIVERSITY COLLEGE OF INFORMATION TECHNOLOGY

IntroductiontoDatabases
Committransac onT1;

PreparedbySkanderTurki

2december2011

[Link] sequenceofqueries. NowbeforetestingthesefeaturesofSQL,weneedtoknowabouttheTRY/[Link]'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 [Link]'slookatourexamplehere:Wewillmakefiveconsecutive inser onsinonetransac [Link] [Link],thentheCATCHblocwillbeexecutedand arollbackwilloccurcancellingallthetransaction. Let'[Link]'sseethecontentoftheProjecttableby executingasimpleselect*:


select*fromproject

Nowwewillforcethepreviouscodetomakeanerrorbytryingtoinserttwoprojectswiththesame idProject,[Link]:
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

[Link] executethesecondInsertanerrorwasraisedbecausewetryedtoinsertanotherprojectwithan [Link] onwhichgaveus [Link] 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;

[Link]'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

[Link]"1row added".Thesecondmessage"0rowadded"wastheanswertooursecondinsertthatdidn'twork. Conclusion: Sonow,whatisthedifferencebetweenthefirstapproach(usingtransactions)andthesecond? Whenwehadanerrorinthefirstexample,[Link]'swhywe didn'[Link](withouttransactions),eachinsertion [Link]'swhythefirstquery executednormallyandthesecondquerydidn'thaveanyeffectontheexecutionofthefirstoneeven ifitraisedanerror. Theuseoftransactionsisusedonlywhenwewanttomakesurethateitheralltheoperationsare doneortheymustallbecancelledifanyundesirablesituationoccurs.

Page

TAIF UNIVERSITY COLLEGE OF INFORMATION TECHNOLOGY

IntroductiontoDatabases

PreparedbySkanderTurki

2december2011

PARTIII:DatabasecreationandmodificationthroughSQLDDL
Nowlet'[Link] [Link]:
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 [Link] asitcandestroyanytablewithallthedataitcontainsinjustthreewords.

ToBeContinuedInchallah..

Page

TAIF UNIVERSITY COLLEGE OF INFORMATION TECHNOLOGY

You might also like