DatabaseSystems
Hans-PetterHalvorsen
S.Adams.Dilbert.Available:http://dilbert.com
OldfashionDatabase(Data-storage)Systems
Nottoolongago,thiswastheonlydata-storagedevicemostcompaniesneeded.Thosedaysareover.
RequirementsAnalysis
Design
Implementation
Testing
Maintenance
Planning
TheSoftwareDevelopment
Lifecycle
Deployment
DatabaseSystemsADatabaseisastructuredwaytostorelotsofinformation.Theinformationisstoredindifferenttables.- “Everything”todayisstoredindatabases!Examples:• Bank/Accountsystems• InformationinWebpagessuchasFacebook,Wikipedia,YouTube,etc.
• Fronter,TimeEdit,etc.• …lotsofotherexamples!
5
DatabaseERDiagramExample:
DatabaseManagementSystems(DBMS)• MicrosoftSQLServer
– Enterprise,Developerversions,etc.(Professionaluse)– Expressversionisfreeofcharge
• Oracle• MySQL (ownedbyOracle,butpreviouslyownedbySunMicrosystems)-
MySQLcanbeusedfreeofcharge(opensourcelicense),WebsitesthatuseMySQL:YouTube,Wikipedia,Facebook
• MicrosoftAccess• IBMDB2• Sybase• MariaDB• MongoDB• etc.
DatabaseTypes• RelationDatabase/SQLDatabases– MicrosftSQLServer– Oracle– MySQL– MariaDB– etc.
• NoSQLDatabases– MongoDB– etc.
8
DatabaseTypesSQLvs.NoSQL
DatabaseModelling
Hans-PetterHalvorsen,M.Sc.
DatabaseModelling
• Thelogicalstructureofthedatabase• ERDiagram(EntityRelationship)
DatabaseDesign– ERDiagramERDiagram(Entity-RelationshipDiagram)• UsedforDesignandModelingofDatabases.• SpecifyTablesandrelationship betweenthem(PrimaryKeysandForeignKeys)
PrimaryKey PrimaryKeyForeignKey
TableName
TableName
RelationalDatabase.InarelationaldatabaseallthetableshaveoneormorerelationwitheachotherusingPrimaryKeys(PK)andForeignKeys(FK).Note!YoucanonlyhaveonePKinatable,butyoumayhaveseveralFK’s.
ColumnNames
Example:
DatabaseDesignTools• Visio• PowerDesigner• CAERwin– CAERwinDataModelerCommunityEdition– CommunityEditionisFree,25objectslimit– SupportforOracle,SQLServer,MySQL,ODBC,Sybase
• ToadDataModeler• ASimpledesignerisalsoincludedwithSQLServer(physicalmodel,notlogicalmodel)
Database- “BestPractice”• Tables:Useuppercaseandsingular formintablenames– notplural,e.g.,
“STUDENT”(notstudents)• Columns:UsePascalnotation,e.g.,“StudentId”• PrimaryKey:
• Ifthetablenameis“COURSE”,namethePrimaryKeycolumn“CourseId”,etc.
• “Always”useInteger andIdentity(1,1) forPrimaryKeys.UseUNIQUEconstraintforothercolumnsthatneedstobeunique,e.g.RoomNumber
• SpecifyRequired Columns(NOTNULL)– i.e.,whichcolumnsthatneedtohavedataornot
• Standardizeonfew/theseDataTypes:int,float,varchar(x),datetime,bit• UseEnglishfortableandcolumnnames• Avoidabbreviations!(UseRoomNumber– notRoomNo,RoomNr,...)
DatabaseDesign– MicrosoftVisio
14
1
2
3
WewilluseVisiotoDesignourDatabase
SelecttheproperTemplate
TableName PrimaryKey(PK)
ForeignKey(FK)
ERDiagramExample- Visio
17
PK PK
PK
PK
PK
PK
FK
FKFK
FKFKFK
PK
PK
FKFK
FKFK
PK-FKRelationship
PK-FKRelationships
TableName
TableName
TableName
TableNameTableName
TableName
TableName TableName
PK– PrimaryKey,FK– ForeignKey
ERDiagramExampleusingbuilt-inDesignerinMicrosoftSQLServer
Hans-PetterHalvorsen,M.Sc.
SQLServer
• Mainparts:SQLServerEngine+ManagementStudio
• SQLServerStandard,Developer,Web,Enterprise,Datacenter,...
• FreeAlternative:SQLServerExpress• SQLAzureDatabase– Cloud-basedversion
MicrosoftSQLServerSQLServerconsistsofaDatabaseEngineandaManagementStudio.TheDatabaseEnginehasnographicalinterface- itisjustaservicerunninginthebackgroundofyourcomputer(preferableontheserver).TheManagementStudioisgraphicaltoolforconfiguringandviewingtheinformationinthedatabase.Itcanbeinstalledontheserverorontheclient(orboth).
MicrosoftSQLServer
1
2
3
4
5
WriteyourQueryhere
TheresultfromyourQuery
YourDatabase
YourTables
YourSQLServer
MicrosoftSQLServer– CreateaNewDatabase
1
2
Nameyoudatabase,e.g.,WEATHER_SYSTEM
MicrosoftSQLServer– TipsandTricks
Makesuretouncheckthisoption!
Doyougetanerrorwhentryingtochangeyourtables?
SQLStructuredQueryLanguage
Hans-PetterHalvorsen,M.Sc.
SQL– StructuredQuerylanguage
• insert into STUDENT (Name , Number, SchoolId)values ('John Smith', '100005', 1)
• select SchoolId, Name from SCHOOL
• select * from SCHOOL where SchoolId > 100
• update STUDENT set Name='John Wayne' where StudentId=2
• delete from STUDENT where SchoolId=3
ADatabaseComputerLanguagedesignedforManagingDatainRelationalDatabaseManagementSystems(RDBMS)QueryExamples:
Wehave4differentQueryTypes(CRUD):INSERT,SELECT,UPDATEand DELETE
CRUD – Create(Insert),Read(Select),UpdateandDelete
CreateTablesusingtheDesignerToolsinSQLServerEvenifyoucando“everything”usingtheSQLlanguage,itissometimeseasiertodosomethinginthedesignertoolsintheManagementStudioinSQLServer.Insteadofcreatingascriptyoumayaswelleasilyusethedesignerforcreatingtables,constraints,insertingdata,etc.
Select“NewTable…”: Next,thetabledesignerpopsupwhereyoucanaddcolumns,datatypes,etc.
1 2
Inthisdesignerwemayalsospecifyconstraints,suchasprimarykeys,unique,foreignkeys,etc.
CreateTableswiththe“DatabaseDiagram”
3
4
5
1 2
YoumayselectexistingtablesorcreatenewTables
CreateNewTable
EnterColumns,selectDataTypes,PrimaryKeys,etc.
if not exists (select * from dbo.sysobjects where id = object_id(N'[SCHOOL]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [SCHOOL](
[SchoolId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,[SchoolName] [varchar](50) NOT NULL UNIQUE,[Description] [varchar](1000) NULL,[Address] [varchar](50) NULL,[Phone] [varchar](50) NULL,[PostCode] [varchar](50) NULL,[PostAddress] [varchar](50) NULL,
) GO
if not exists (select * from dbo.sysobjects where id = object_id(N'[CLASS]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [CLASS](
[ClassId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,[SchoolId] [int] NOT NULL FOREIGN KEY REFERENCES [SCHOOL]
([SchoolId]),[ClassName] [varchar](50) NOT NULL,[Description] [varchar](1000) NULL,
) GO
CreateTablesusingSQL
GetDatafrommultiple tablesinasingleQueryusingJoins
selectSchoolName,CourseNamefromSCHOOLinnerjoinCOURSEonSCHOOL.SchoolId =COURSE.SchoolId
Example:
YoulinkPrimaryKeysandForeignKeystogether
CreatingViews usingtheEditor
1
2
3
4Addnecessarytables
SavetheView
GraphicalInterfacewhereyoucanselectcolumnsyouneed
CreatingViews usingSQL
31
IF EXISTS (SELECT nameFROM sysobjectsWHERE name = 'CourseData' AND type = 'V')
DROP VIEW CourseDataGO
CREATE VIEW CourseDataAS
SELECTSCHOOL.SchoolId, SCHOOL.SchoolName, COURSE.CourseId, COURSE.CourseName,COURSE.Description
FROMSCHOOL INNER JOIN COURSE ON SCHOOL.SchoolId = COURSE.SchoolIdGO
YoucanUsetheViewasanordinarytableinQueries:
AViewisa“virtual”tablethatcancontaindatafrommultipletables
InsidetheViewyoujointhedifferenttablestogetherusingtheJOIN operator
TheNameoftheView
CreateView:
UsingtheView:select * from CourseData
StoredProcedureIFEXISTS(SELECTname
FROMsysobjectsWHEREname ='StudentGrade'AND type='P')
DROPPROCEDUREStudentGradeOG
CREATEPROCEDUREStudentGrade@Studentvarchar(50),@Coursevarchar(10),@Gradevarchar(1)
AS
DECLARE@StudentId int,@CourseId int
selectStudentIdfromSTUDENTwhereStudentName =@Student
selectCourseId fromCOURSEwhereCourseName =@Course
insertintoGRADE(StudentId,CourseId,Grade)values (@StudentId,@CourseId,@Grade)GO
execute StudentGrade 'John Wayne', 'SCE2006', 'B'
AStoredProcedureislikeMethodinC#- itisapieceofcodewithSQLcommandsthatdoaspecifictask– andyoureuseit
InputArguments
Internal/LocalVariables
ProcedureName
SQLCode(the“body”oftheStoredProcedure)
Note!Eachvariablestartswith@
CreateStoredProcedure:
UsingtheStoredProcedure:
Trigger
IF EXISTS (SELECT nameFROM sysobjectsWHERE name = 'CalcAvgGrade' AND type = 'TR')
DROP TRIGGER CalgAvgGradeGO
CREATE TRIGGER CalcAvgGrade ON GRADEFOR UPDATE, INSERT, DELETEAS
DECLARE@StudentId int,@AvgGrade float
select @StudentId = StudentId from INSERTED
select @AvgGrade = AVG(Grade) from GRADE where StudentId = @StudentId
update STUDENT set TotalGrade = @AvgGrade where StudentId = @StudentId
GO
ATriggerisexecutedwhenyouinsert,updateordeletedatainaTablespecifiedintheTrigger.
InsidetheTriggeryoucanuseordinarySQLstatements,createvariables,etc.
NameoftheTrigger
SpecifywhichTabletheTriggershallworkon
Internal/LocalVariablesSQLCode(The“body”oftheTrigger)
SpecifywhatkindofoperationstheTriggershallacton
Note!“INSERTED”isatemporarilytablecontainingthelatestinserteddata,anditisveryhandytouseinsideatrigger
CreatetheTrigger:
Summary• DBMS – DatabaseManagementSystem• SQL – StructuredQueryLanguage.ADatabaseComputerLanguagedesignedforManagingDatainRelationalDatabaseManagementSystems(RDBMS)
• ERDiagram– EntityRelationship.UsedforDesignandModelingofDatabases.SpecifyTablesandrelationshipbetweenthem(PrimaryKeysandForeignKeys)
References• NTNU.(2013).TDT4140Systemutvikling.Available:
http://www.ntnu.no/studier/emner/TDT4140• UiO.(2013).INF1050- Systemutvikling.Available:
http://www.uio.no/studier/emner/matnat/ifi/INF1050/• O.Widder.(2013).geek&poke.Available:http://geek-and-poke.com• B.Lund.(2013).Lunch.Available:http://www.lunchstriper.no,
http://www.dagbladet.no/tegneserie/lunch/• S.Adams.Dilbert.Available:http://dilbert.com
Hans-PetterHalvorsen,M.Sc.
UniversityCollegeofSoutheastNorwaywww.usn.no
E-mail:[email protected]:http://home.hit.no/~hansha/