mta : database fundamentals · proficiency assessment : scenario 2-4 (pg 42 of guidebook) you are a...
TRANSCRIPT
MTA : Database Fundamentals
Lab Exercises & Notes
LabExercise1
Task1:ExploringSQLServerManagementStudio(SSMS)
1. Onthevirtualmachine’sWindowstaskbarofyourVirtualMachine,startSQLServerManagementStudio.
2. Atthe“SQLServer”Window,connecttoMIA-SQLdatabaseengineusingWindows
Authenticationasfollows:
3. IftheObjectExplorerisnotvisible,ontheViewmenu,clickObjectExplorer.
4. IntheObjectExplorer,underMIA-SQL,expandDatabasesandnotethedatabasesthatare
hostedonthisdatabaseengineinstance:
a. SystemDatabasesarecreatedbydefault:master,model,msdbandtempdb.
ThesedatabasesareusedbySQLServerforitsownmaintenanceandmanagement.
b. Therestareuser-defineddatabases.WewillbeusingtheAdventureWorksdatabaseforourcourse.1) ExpandtheAdventureWorksdatabase.
Youwillseethedatabaseobjectsinthatdatabase.
2) ExpandtheTablestoseethelistoftablesthatareinthedatabase.Youwillseetableslike:
- HumanResources.Department- HumanResources.Employee- Person.Address- …
NotethattheAdventureWorksnamingconventionisschema_name.table_name
3) LookforthePerson.Persontable.Right-clickonitandchooseSelectTop1000Rows.
4) Youwillsee2newwindows:SQLQuerywindowandtheResultswindowthatdisplaysthedatainthePerson.Persontable.
5) MinimizetheAdventureWorksdatabase.
Task2:CreateaDatabasewiththeSSMSinterface
1. UnderMIA-SQL,rightclickDatabasesandselectNewDatabase.
2. EnterLabDatabase.ClickOK.
3. VerifythatthenewdatabasehasbeencreatedintheObjectExplorer.Task3:DeleteaDatabasewiththeSSMSinterface
1. UnderDatabases,selectLabDatabaseandright-clickDelete.2. SelectCloseExistingConnectionsthenclickOK.3. VerifythattheLabDatabaseisnolongerlistedintheObjectExplorer.
Note:ClickDatabasesandright-clickRefreshifnecessary.
1
LabExercise2
Task1:Createa“LabDatabase”databaseusingSSMS
1. UnderMIA-SQL,rightclickDatabasesandselectNewDatabase.2. EnterLabDatabase.ClickOK.3. VerifythatthenewdatabasehasbeencreatedintheObjectExplorer.
Task2:CreateatableusingSSMS
CreateanewTablePlanetswiththefollowingfields:
1. ExpandtheLabDatabase.
2. Right-clicktheTablefolderandselectNewTable.
3. EnterdetailsforColumnName,DatatypeandLength.IndicateonAllowNullsaccordingly:ForIndividualIDcolumn:• Right-clickthe►iconandclickSetPrimaryKey.• Expand(click>)theIdentitySpecificationintheColumnPropertieswindowbelow.• Set(IsIdentity)toYes• CheckthatIdentityIncrementandIdentitySeedhasbeensetto1.
Thiswillinsertanauto-incrementnumberforeachnewrecordstartingfrom1.ForDateCreatedcolumn:• IntheColumnPropertieswindowbelow,expand(General).• UnderDefaultValueorBinding,entergetdate()–thiswillinsertthecurrentdatefor
eachnewrecord.
4. SaveyourtablebyselectingFile>SaveTable_1.EnternameoftableasPlanetsandclickOK.
5. DoaRefreshonLabDatabase.VerifythatyourtablehasbeencreatedintheObjectExplorer.
2
Task3:AlterTableusingSSMS
YourealizedthedatatypeforRadiusshouldbefloatinsteadofvarchar(50).Modifyitsdatatypeasfollows:1. SelectthePlanetstablewithintheLabDatabasedatabase.
2. Right-clickDesign
3. AmendthedatatypeofRadiustofloat.
4. Saveyourchangesbyclickingthe“Save”icon.
Note:
Ifyouencountera“Savingschangesnotpermitted”error,followthesesteps:• OntheToolsmenu,clickOptions.• InthenavigationpaneoftheOptionswindow,clickDesigners.• Uncheck“Preventsavingchangesthatrequirethetablere-creation”checkbox.ClickOK.
Task4:DropTableusingSSMS
Todeleteaselectedtable,simplyright-clickandselect“Delete”.Task5:CreateatableusingTRANSACT-SQLcommands
1. Clickthe“NewQuery”icon.
Tip:ChangethefontsizeoftheSQLQueryEditor
1. ClickonToolsmenu,selectOptions….
2. ExpandEnvironment(clickon>)andthenclickFontsandColors.
3. IntheShowsettingsforlist,selectTextEditor.
4. Changethefontandsizeasdesired.
5. ClickOK.
2. EnterthefollowingSQLcommandsintheSQLQuerywindow:
3
3. Clickonthe“Execute”icon.
4. DoaRefreshonLabDatabase.VerifythatyourtablePlanets1hasbeencreatedintheObject
Explorer.
5. SaveyourSQLcommandsinascriptfileasfollows:- ClickFile>SaveSQLQuery.sqlAs…- Clickthedesktopfolderandenter“Lab2_CreateTable.sql”forthefilename.
Task6:AlterTableusingTRANSACT-SQLcommands
ThedatatypeforRadiusshouldbefloatinsteadofvarchar(50).Modifyitsdatatypeasfollows:1. EnterthefollowingSQLcommandsintheSQLQuerywindow:
ALTER TABLE Planets1 ALTER COLUMN Radius float;
2. Highlightwhatyouhaveeditedandclickonthe“Execute”icon.
3. ClickPlanets1ontheObjectExplorerthenright-clickDesign.VerifythattheRadiuscolumnhasbeensettothefloatdatatype.(DoaRefreshonthedatabaseifnecessary)
Task7:DropTableusingTRANSACT-SQLcommands
IfyouneedtoremovethePlanets1table,youcanrunthefollowingTRANSACT-SQLcommands:
DROP TABLE Planets1;
4
SETUPtouse“Adventureworks”Databaseforexercises
1. Clickthe“NewQuery”icon.
2. EnterthefollowingSQLcommandsintheSQLQuerywindow: ALTER AUTHORIZATION ON DATABASE::AdventureWorks TO sa ;
Task8:CreateaViewusingSSMS
CreateanewviewvwCustomerfromtheSales.CustomertableoftheAdventureWorksdatabasewiththefollowingfields:CustomerID,StoreID,AccountNumber.1. SelectViewundertheAdventureWorksdatabase.
2. Right-clickNewView
3. SelectthetableCustomer(Sales).ClickAddthenClosethewindow.
4. Selectthefollowingcolumns:
• CustomerID• StoreID• AccountNumber
5. ClicktheSaveicontosaveyourview.
6. EntervwCustomerfortheviewname.ClickOK.
7. DoaRefreshonAdventureWorks.
8. VerifythatyourviewhasbeencreatedintheObjectExplorer.UseSSMS’s“Selecttop1000rows”orwriteasimpleSQLSelectquerytoseethecontentsofthevwCustomer.
Task9:DeleteaViewusingSSMS
Todeleteaselectedview,simplyright-clickandselect“Delete”.
5
Task10:CreateaViewusingTRANSACT-SQLcommands
CreateanewviewvwIndividualfromthePerson.PersontableoftheAdventureWorksdatabasewiththefollowingfields:FirstName,LastName,PersonType.1. Clickthe“NewQuery”icon.2. EnterthefollowingSQLcommandsintheSQLQuerywindow:
USE AdventureWorks; CREATE VIEW vwIndividual AS SELECT FirstName, LastName, PersonType FROM person.person WHERE PersonType = 'IN';
3. Clickonthe“Execute”icon.
4. DoaRefreshonAdventureWorksdatabase.VerifythatyourviewvwIndividualhasbeencreatedintheObjectExplorer.
5. WriteasimpleSQLSelectquerytoseethecontentsofvwIndividual.Task11:DropViewusingTRANSACT-SQLcommands
IfyouneedtoremovethevwIndividualview,youcanrunthefollowingTRANSACT-SQLcommands:
DROP VIEW vwIndividual;
6
Task12:CreateStoredProcedureusingSSMSCreateanewstoredproceduretoretrievethefollowingfields:FirstName,LastName,PersonTypefromthePerson.PersontableoftheAdventureWorksdatabase.1. ExpandtheProgrammabilityfolderundertheAdventureWorksdatabase.
2. ExpandtheStoredProcedurefolder.YouwillseeSystemStoredProcedureswhichare
providedbyMicrosoft.
3. Right-clickStoredProceduresandchooseNewStoredProcedure.4. TheTextEditorwindowwillopenanddisplayaready-madestoredproceduretemplatefor
you.5. Aswewillbewritingasimplestoredprocedure,wewillstartwithanewSQLquerywindow.
Clickthe“NewQuery”icon.6. EnterthefollowingintheSQLQuerywindow:
CREATE PROCEDURE uspGetPerson
AS BEGIN SET NOCOUNT ON; SELECT FirstName, LastName, PersonType FROM person.person WHERE PersonType = 'IN'; END
7. Clickonthe“Execute”icontocreatethestoredprocedure.
8. DoaRefresh.VerifythatthestoredprocedureuspGetPersonhasbeencreatedintheObject
Explorer.9. Torunthestoredprocedure,openanewSQLQuerywindowandenter:
exec uspGetPerson;
Note:PressCtrl-Shift-Rtorefreshthecacheifnecessary.
Thisturnsoffthe“Numberofrowsaffected”message
1
LabExercise3 Task1:UsingtheSELECTstatementProficiencyAssessment:Scenario2-4(Pg42ofGuidebook)YouareadatabaseadministratorfortheAdventureWorksCorporationandaservicemanagerneedsyourhelptoextractdatafromthecompany’sdatabase.Therefore,afteropeningSSMSandaccessingtheAdventureWorksdatabase,specifythebasicSELECTstatementsyouwouldusetoretrievetherequiredinformationfromtheProductsSubcategorytable.1. WhatcommandswouldreturnalltherowsandcolumnsintheProductCategorytable?
USE AdventureWorks;
SELECT * FROM Production.ProductCategory;
2. WhatcommandswouldyoutypeandexecutetoreturnonlytheProductSubcategoryID,
ProductCategoryID,Name,andModifiedDatecolumns? SELECT ProductSubcategoryID, ProductCategoryID, Name, ModifiedDate FROM Production.ProductSubcategory;
3. Whatcommandswouldyoutypeandexecutetoreturnrowswherethewordbikeisfound
somewhereintheNamecolumn? SELECT ProductSubcategoryID, ProductCategoryID, Name, ModifiedDate FROM Production.ProductSubcategory WHERE Name LIKE '%bike%';
4. Intheexistingquerywindow,whatcommandswouldyouusetoaddacolumnaliastothe
Namecolumntoclarifyitasthesubcategoryname? SELECT ProductSubcategoryID, ProductCategoryID, Name AS 'Subcategory Name', ModifiedDate FROM Production.ProductSubcategory WHERE Name LIKE '%bike%';
5. Intheexistingquerywindow,whatcommandwouldyouusetosortthepreviousresultsetbySubcategoryName? SELECT ProductSubcategoryID, ProductCategoryID, Name AS 'Subcategory Name', ModifiedDate FROM Production.ProductSubcategory WHERE Name LIKE '%bike%' ORDER BY 'Subcategory Name';
2
Task2:CreatetheHumanResources.EmployeetableUseeitherSSMSorTRANSACT-SQLtocreatetheHumanResources.Employeetable.
1. CreateClickonthe“NewQuery”icon.
2. EnterthefollowingSQLcommandsintheSQLQuerywindow:USE LabDatabase; CREATE TABLE [HumanResources.Employee] ( EmployeeID int NOT NULL PRIMARY KEY, FirstName varchar(50) NULL, LastName varchar(50) NULL, Title varchar(20) NULL, EmailAddress varchar(100) NULL ); 3. Clickonthe“Execute”icon.
4. DoaRefreshonLabDatabase.VerifythatyourtableHumanResources.Employeehasbeen
createdintheObjectExplorer.Task3:Insert/UpdatedatatoHumanResources.EmployeetableusingSSMSEnterthefollowingrowsofdatatotheHumanResources.Employeetable:EmployeeID FirstName LastName Title EmailAddress287 Mensa-Annan Tete Mr. [email protected] Abbas Syed Mr. [email protected] Valdez Rachel NULL [email protected]. AttheObjectExplorer,right-clickHumanResources.Employeeandselect“EditTop200
Rows”.
2. Enterthedata(asshownabove)intothetable.Task4:InsertdatausingTRANSACT-SQLcommandsTheothermethodtoinsertdataisbyrunningaSQLINSERTcommand.1. Clickonthe“NewQuery”icon.2. EnterthefollowingSQLcommandsintheSQLQuerywindow: INSERT INTO [HumanResources.Employee] ( EmployeeID, FirstName, LastName, Title, EmailAddress ) VALUES (290, 'Karen', 'Yap', 'Dr.', '[email protected]'), (211, 'Lin Lee', 'Kim','Ms.', NULL);
3
3. Clickonthe“Execute”icon.4. DoaRefreshonLabDatabase.VerifythatyourtableHumanResources.Employeehasthe
correctdatainserted.Task5:UpdatedatausingTRANSACT-SQLcommandsYourealizedthatthereisadata-entryerrorintheEmployeeIDandanupdateinEmailAddressofstaffKimLinLi.(EmployeeIDshouldbe291andnewEmailAddressis‘[email protected]’).MakethenecessaryamendmentsusingtheUpdatecommand.1. Clickonthe“NewQuery”icon.2. EnterthefollowingSQLcommandsintheSQLQuerywindow:
UPDATE [HumanResources.Employee] SET EmployeeID = 291, EmailAddress = '[email protected]' WHERE EmployeeID = 211;
Task6:Deletedata(FORINFOONLY)
• ToremoveaspecificrecordofanytableusingSSMS:1. AttheObjectExplorer,right-clickthetableandselect“EditTop200Rows”.2. Selecttheentirerowtobedeleted(leftmostcolumn►icon)andright-clickDelete.
• ToremoveanytableusingSSMS:
1. AttheObjectExplorer,right-clickthetableandselect“Delete”.
• ToremovetableusingusingTRANSACT-SQLcommands1. IfyouwishtoremoveHumanResources.Employeetable,enterandexecutethe
followingSQLcommandsintheSQLQuerywindow:
-- Removes all rows in the table only DELETE FROM [HumanResources.Employee]; -- Removes the table completely DROP TABLE [HumanResources.Employee];
1
LabExercise4Task1:CreateaForeignKeyusingSSMSYouaretaskedtocreateanEmployeetablewithemployeedetailsandtocreatealinktotheDepartmenttablewhichcontainsthedepartmentnameanditsmanager.Departmenttableistheprimarytable.1. CreatethefollowingtablesinLabDatabaseusingTRANSACT-SQLorSSMS:
USE LabDatabase; -- Create Employee CREATE TABLE Employee ( EmployeeID int NOT NULL PRIMARY KEY, FirstName varchar(50) NULL, LastName varchar(50) NULL, Title varchar(20) NULL, Dept varchar(5) NULL, EmailAddress varchar(MAX) NULL ); -- Create Department CREATE TABLE Department ( Dept varchar(5) NOT NULL PRIMARY KEY, DeptName varchar(50) NULL, ManagerID int NULL); 2. InObjectExplorer,refreshtheLabDatabase>Tablesfolder.
3. ExpandtheLabDatabase>Tablesfolder.
4. Right-clickEmployeeandselectDesign.
2
5. SelectRelationshipsfromtheTableDesignerdrop-downmenunearthetopofthescreenas
shownbelow:
6. ClicktheAddbutton.
7. Clicktheellipsis(...)besidetheTableandSpecificationpropertydialogboxasshownbelow:
3
8. Selectthetablethatyourforeignkeyreferstointheprimarykeytable(Department)andits
attributeDeptinthedrop-downlistsasshownbelow:
9. TheForeignkeytableshouldbeEmployeeanditsattributeDeptastheforeignkey.10. ClickOKtoclosethedialogbox.11. ClicktheClosebutton.12. SaveyournewlycreatedconstraintbyselectingSaveAllfromtheFilemenu.Task2:CreateaForeignKeyusingTRANSACT-SQLAlternatively,youcancreateatablewithaforeignkeyconstraintusingSQL.ThefollowingcreatestheCustomertablewithaforeignkeythatlinkstotheDepartmenttable.Departmenttableistheprimarytable.
USE LabDatabase; -- Create Customer CREATE TABLE Customer ( CustID int NOT NULL PRIMARY KEY, FirstName varchar(50) NULL, LastName varchar(50) NULL, Title varchar(20) NULL, Dept varchar(5) NULL FOREIGN KEY REFERENCES Department(Dept), EmailAddress varchar(MAX) NULL );
4
Task3:GenerateDatabaseDiagramusingSSMSYoucanusetheDatabaseDiagramsfunctioninSSMStogenerateadiagramtoshowhowthetablesinyourdatabasearerelated.
1. Closeallthetables.2. InObjectExplorer,refreshtheLabDatabasefolder.
3. SelectLabDatabase>Database
Diagramfolder.Right-clickandselectNewDatabaseDiagram.
4. AttheAddTablewindow,click
Refresh.
5. SelectDepartmentandclickAdd.SelectEmployeeandclickAdd.SelectCustomerandclickAdd.
6. ClickClose.Clickoutsidethebox.7. Youshouldbeabletoseethefollowingdatabasediagramgenerated,showingthe
relationshipsbetweenthethreetables:
5
Task4:CreateaNon-ClusteredIndexusingSSMSYourusersinformedyouthatbesidestheCustID(primarykey),theyalsofrequentlysearchforcustomerinformationusingthenameofthecustomer.Createanon-clusteredindextospeedupretrievalofcustomerdatausingtheirfirstandlastnames.1. IntheObjectExplorer,expandLabDatabasedatabaseanditsTables.2. ExpandtheCustomertable.3. ExpandIndexes.4. NotethataClustered-indexonCustID(theprimarykey)hasalreadybeencreatedforthe
CustomertablebySQLServer.DoubleclickonPK_Customer_xxxx…toseeitsdetails.
5. ClickCancelandclicktheminus(-)iconofIndexes.6. Right-clickIndexes>NewIndex>Non-ClusteredIndex…
6
7. ClickAddandselectFirstNameandLastNameasthecolumnstocreatenon-clusteredindex.
8. ClickOK.ConfirmbyclickingOKagain.
9. NotethatyourNon-clusteredIndexhasbeencreatedsuccessfullyintheObjectExplorer.
10. BycreatingindexesonCustID(clustered),FirstNameandLastName(non-clustered),itmeansthatanysubsequentdataretrievalusingtheanyofthe3fieldswillbefasterthanwithoutanyindexescreated.
1
2
3
4
5
6