Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL...

94
Database Overview Hans-Petter Halvorsen, M.Sc. Introduction to Database Systems, ERwin, SQL Server, SQL, etc.

Transcript of Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL...

Page 1: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

DatabaseOverview

Hans-PetterHalvorsen,M.Sc.

IntroductiontoDatabaseSystems,ERwin,SQLServer,SQL,etc.

Page 2: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

Contents• DatabaseModelling/DesignusingERwin• GenerateSQLTableScriptusingERwin• GenerateTablesinSQLServerusingtheSQLScriptgeneratedbyERwin

• UseStructuredQueryLanguage(SQL)• CreateStoredProcedures,View,Triggers• DatabaseCommunicationinLabVIEW• DatabaseCommunicationinC#

Page 3: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

NecessarySoftware

• ERwin (CAERwinDataModelerCommunityEdition,freedownloadfromInternet)

• SQLServer(Express)Edition(DownloadforfreefromInternetorDreamSpark:“SQLServerxxxx ExpresswithTools”)

• LabVIEW• DAQmxDriverSoftware• LabVIEWSQLToolkit(©Hans-PetterHalvorsen)• VisualStudio

MakesuretoinstallthenecessarySoftwarebeforeyougotothelaboratory!

Software

Page 4: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

RecommendedLitterature• Tutorial:IntroductiontoLabVIEW

http://home.hit.no/~hansha/?page=labview• Tutorial:IntroductiontoDatabaseSystems

http://home.hit.no/~hansha/?tutorial=database• Tutorial:StructuredQueryLanguage(SQL)

http://home.hit.no/~hansha/?tutorial=sql• Tutorial:DatabaseCommunicationinLabVIEW

http://home.hit.no/~hansha/?tutorial=database_labview• Tutorial:UsingSQLServerinC#• Tutorial:IntroductiontoVisualStudioandC#

http://home.hit.no/~hansha/?tutorial=csharp• Tutorial:DataAcquisitioninLabVIEW

http://home.hit.no/~hansha/?tutorial=daq

Page 5: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

DatabaseSystems

Hans-PetterHalvorsen,M.Sc.

https://www.youtube.com/watch?v=n75iPNrzN-o

Page 6: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

OldfashionDatabase(Data-storage)Systems

Nottoolongago,thiswastheonlydata-storagedevicemostcompaniesneeded.Thosedaysareover.

Page 7: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

DatabaseSystemsADatabaseisastructuredwaytostorelotsofinformation.Theinformationisstoredindifferenttables.- “Everything”todayisstoredindatabases!Examples:• Bank/Accountsystems• InformationinWebpagessuchasFacebook,Wikipedia,YouTube,etc.

• Fronter,TimeEdit,etc.• …lotsofotherexamples!

Theory

Page 8: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

DatabaseManagementSystems(DBMS)• MicrosoftSQLServer

– Enterprise,Developerversions,etc.(Professionaluse)– Expressversionisfreeofcharge

• Oracle• MySQL (ownedbyOracle,butpreviouslyownedbySun

Microsystems)- MySQLcanbeusedfreeofcharge(opensourcelicense),WebsitesthatuseMySQL:YouTube,Wikipedia,Facebook

• MicrosoftAccess• IBMDB2• Sybase,etc.(wehavehundredsdifferentDBMS)

WewilluseSQLserverbecauseitisverypopular intheindustry today,andwecanuseitforfreeviatheMicrosoftDreamSparkPremiumSubscription – whichisavailableforthestudentsandstaffatTelemarkUniversityCollege,orusetheExpressversionwhichisavailableforfreeforeverybody.

Theory

Page 9: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

MicrosoftSQLServerSQLServerconsists ofaDatabaseEngineandaManagementStudio.TheDatabaseEnginehasnographicalinterface- itisjustaservicerunninginthebackgroundofyourcomputer(preferableontheserver).TheManagementStudioisgraphicaltoolforconfiguring andviewingtheinformation inthedatabase.Itcanbeinstalledontheserverorontheclient(orboth).

SoftwareSoftware

Page 10: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

ERwin

Hans-PetterHalvorsen,M.Sc.

DatabaseDesign&Modelling

https://www.youtube.com/watch?v=P3n6hRNup8Y

Page 11: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

CAERwinDataModelerCommunityEdition• Free!• Max25Tables(goodenoughforourpurpose)• Downloadhere:http://erwin.com/products/data-modeler/community-edition

Software

Page 12: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

DatabaseDesign– ERDiagramERDiagram(Entity-RelationshipDiagram)• UsedforDesignandModelingofDatabases.• SpecifyTablesandrelationship betweenthem(PrimaryKeysandForeignKeys)

PrimaryKey PrimaryKey ForeignKey

TableName

TableName

RelationalDatabase.InarelationaldatabaseallthetableshaveoneormorerelationwitheachotherusingPrimaryKeys(PK)andForeignKeys(FK).Note!Youcanonly haveonePKinatable,butyoumayhaveseveralFK’s.

ColumnNames

Example:

Theory

Page 13: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

Database- “BestPractice”• Tables:Useuppercaseandsingular formintablenames– notplural,e.g.,

“STUDENT”(not“students”)• Columns:UsePascalnotation,e.g.,“StudentId”• PrimaryKey:

• Ifthetablenameis“COURSE”,namethePrimaryKeycolumn“CourseId”,etc.• “Always”useInteger andIdentity(1,1) forPrimaryKeys.UseUNIQUE

constraintforothercolumnsthatneedstobeunique,e.g.“RoomNumber”• SpecifyRequired Columns(NOTNULL)– i.e.,whichcolumnsthatneedtohave

dataornot• Standardizeonfew/theseDataTypes:int,float,varchar(x),datetime,bit• UseEnglishfortableandcolumnnames• Avoidabbreviations!(Use“RoomNumber”– not“RoomNo”,“RoomNr”,...)

Itisrecommended thatyoufollowtheseguidelines!

Page 14: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

IntroductiontoERwinOpenERwinandselectFile->New...Thefollowingwindowappears(NewModel):

SelecttheDatabaseTypeandVersionyoushalluse

Makesuretoselect“Logical/Physical”Model

Software

Page 15: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

IntroductiontoERwin

“Landscape”orientationisrecommended

Page 16: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

IntroductiontoERwin

TrytocreatethefollowingTables,Columns,PrimaryKeysandForeignKeysusingERwin:

Page 17: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

IntroductiontoERwinUsethe“Entity”Tool inorder

toCreateNewTables

Use<Tab>and<Enter>inordertogivetheTablesaNameandtocreateColumns.

Usethe<Arrows>toswitchbetweentheColumns insideaTable

How-To:CreateTablesandColumns

Page 18: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

IntroductiontoERwinUsethe“Relationship”Toolinorder

toCreateaPrimaryKey(PK)–ForeignKey(FK)Relationship

ClickfirstonthePKtableandthenontheFKtableusing the“Relationship”Tool.TheRelationshipConnectionandtheFK

column itselfisthenCreatedAutomatically

How-To:CreatePrimaryKey(PK)– ForeignKey(FK)Relationships:

Page 19: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

SettingDataTypes(PhysicalModel)

YoumayalsoDouble-click(orRight-clickandselectTable/ColumnProperties)onTablesandColumns inorder tochangedifferent

Attributes,eg.DataTypes,etc.

MakesuretosetproperDataTypes

Page 20: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

20

FinalResults:

Page 21: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

CreatingTABLEScript

21

Makesureyou areusingthePhysicalModel

How-To:CreateaSQLScriptSelect“ForwardEngineering”

and“Schema...”

Select/DeselectdifferentOptionsinordertomakeyourscriptthewayyouwant.Click “Preview”in

ordertoseetheresults.

Click“Save”whenyouaresatisfiedwithyourScript

1

2

3

4

Page 22: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

22

TrytoCreatethisExampleusingERwin.FindproperDataTypesinthePhysicalModel

DatabaseDesignExercise

Page 23: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

Congratulations!- YouarefinishedwiththeExample

Page 24: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

SQLServer

Hans-PetterHalvorsen,M.Sc.

DatabaseImplementation

https://www.youtube.com/watch?v=SlR4KOhAG1U

Page 25: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

SQLServer2014InstallationSQLServerhasdifferentEditionsandInstallationPackages.Herewewillgothrough theinstallationofSQLServer2014ExpresswithTools.Preparation1:DownloadInstallationPackage(SQLServer2014ExpresswithTools)fromInternetorDreamSparks.Preparation2:AreyouusingWindows8/10?– Youmayneedtoinstallthe.NETFramework3.5inadvance:

Note!Ittakessometimetodownload, somakesuretodo itbeforetheLabWork inClass!!

• GotoSettings.Choose ControlPanelthenchoose Programs.• ClickTurnWindows featuresonoroff,andtheuserwillsee

Windows featurewindow.• Youcanenablethisfeaturebyclickon.NETFramework3.5(include

.NET2.0and3.0)selectitandclickOK.Afterthisstep,itwilldownload theentirepackagefrominternetandinstallthe.NETFramework3.5feature.

Software

Page 26: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

26

StartInstallingSQLServer2014ExpresswithToolsStep1

Step2(JustClickNext)

Note!ThesescreenshotsarefromSQLServer2012– butSQLServer2014issimiliar

Page 27: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

27

Step3(JustClickNext)

Step4(JustClickNext)

Page 28: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

28

Step5(UseDefaultorchangetheNameifyouwantto)

Step6(JustClickNext)

Page 29: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

29

Step7(Select“MixedMode”)

Step7b(useDefaultlocationorchangefolderfortheDatabaseFiles)

EnterPasswordfor“sa”userandmakesuretorememberit!!

“MixedMode”isrecommended

Page 30: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

30

Step8(JustClickNext)

Step9– Finished!

HopefullyareallGreen(Succeeded)YouarenowreadytouseSQLServer

Page 31: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

MicrosoftSQLServerManagementStudio

WriteyourQueryhere

TheresultfromyourQuery

YourDatabase

YourTables

YourSQLServer

Software

1

2

3

4

5

Page 32: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

MicrosoftSQLServer– CreateaNewDatabase

32

Nameyoudatabase,e.g.,“SCHOOL”1

2

Page 33: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

33TrytoCreatetheseTablesinSQLServer(eithermanuallyorfromtheScriptfromERwin)

DatabaseDesignExercise

Page 34: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

OpenSQLServerandcreatea“NewDatabase...”1 SQLServer

2

OpentheSQLScriptinordertoinserttheTablesinSQLServer

3 YouareFinished. Youarereadytostartusingthe

database,insertingdata,etc.

Page 35: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

35

MicrosoftSQLServer

Makesuretouncheckthisoption!

Doyougetanerrorwhentryingtochangeyourtables?

Page 36: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

CreateTablesusingtheDesignerToolsinSQLServer

Evenifyoucando“everything”usingtheSQLlanguage, itissometimeseasiertodosomething inthedesigner toolsintheManagementStudio inSQLServer.Insteadofcreatingascriptyoumayaswelleasilyusethedesigner forcreatingtables,constraints,insertingdata,etc.

Select“NewTable…”:

Next,thetabledesignerpopsupwhereyoucanaddcolumns, datatypes,etc.

Inthisdesignerwemayalsospecifyconstraints,suchasprimarykeys,unique, foreignkeys,etc.

12

Page 37: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

CreateTableswiththe“DatabaseDiagram”

37

YoumayselectexistingtablesorcreatenewTables

CreateNewTable

EnterColumns, selectDataTypes,PrimaryKeys,etc.

1 2

3

4

5

Page 38: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

Congratulations!- YouarefinishedwiththeExample

Page 39: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

StructuredQueryLanguageSQL

Hans-PetterHalvorsen,M.Sc.

Page 40: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

WhatisSQL?• SQL– StructuredQueryLanguage• SQLisastandardlanguageforaccessingdatabases– andmanipulatedata

• SQLisnotcasesensitive

select SchoolId, Name from SCHOOL

ColumnsTable

Example:

Weusethe“SELECT”commandinordertogetdatafromtheDatabase

Theory

Page 41: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

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

QueryExamples:

Wehave4differentQueryTypes:INSERT,SELECT,UPDATEand DELETE

Theory

Page 42: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

ImportantSQLCommands• SELECT- extractsdatafromadatabase• UPDATE- updatesdatainadatabase• DELETE- deletesdatafromadatabase• INSERTINTO- insertsnewdataintoadatabase

• CREATEDATABASE- createsanewdatabase• ALTERDATABASE- modifiesadatabase• CREATETABLE- createsanewtable• ALTERTABLE- modifiesatable• DROPTABLE- deletesatable• CREATEINDEX- createsanindex(searchkey)• DROPINDEX- deletesanindex

Theory

TheseareusedwhencreatingormodifyingexistingTables

Thesearemostusedinyourdailywork.Thesecommandsareusedtoinsertormodifydata

Page 43: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

SQL

DDL DML

StructuredQueryLanguage(SQL)

DataDefinition Language(DDL) DataManipulation Language(DML)

Create Drop

Rename Alter

CRUD

CREATETables DELETETables

RENAMETables ALTERTables

CreateRead

UpdateDelete

INSERTINTO

SELECT

UPDATE

DELETE

2maingroupsofSQLCommands

Mostusedindailywork

Page 44: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

CreateTablesusingSQLCREATE TABLE SCHOOL(

SchoolId int IDENTITY(1, 1) NOT NULL PRIMARY KEY,SchoolName varchar(50) NOT NULL UNIQUE,Description varchar(1000) NULL,Address varchar50) NULL,Phone varchar(50) NULL,PostCode varchar(50) NULL,PostAddress varchar(50) NULL,

) GO......

Example:

Page 45: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

SQLQueries

TrytoCreatethefollowingTableandDatausingSQL

TableName:CUSTOMER

Page 46: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

INSERT

INSERTINTOCUSTOMER(CustomerName,ContactName,Address,City,PostalCode,Country)VALUES('Cardinal','TomB.Erichsen','Skagen21','Stavanger','4006','Norway');

Page 47: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

SELECTTrytoWriteandExecutethefollowingQueries

SELECT*FROMCUSTOMER

SELECT*FROMCUSTOMERWHERECustomerID=1

SELECTCustomerName,CityFROMCUSTOMER

SELECTDISTINCTCityFROMCUSTOMER

SELECT*FROMCUSTOMERWHERECountry='Mexico'

Note!SQLisNOTcasesensitive:“select”isthesameas“SELECT”

SELECT*FROMCUSTOMERWHERECountry='Germany’ ANDCity='Berlin'

SELECT*FROMCUSTOMERWHERECity='Berlin’ORCity=’Luleå'

SELECT*FROMCUSTOMERORDERBYCountry

SELECT*FROMCUSTOMERORDERBYCountryDESC

Page 48: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

UPDATETrytoWriteandExecutethefollowingQuery

UPDATECUSTOMERSETContactName='AlfredSchmidt',City='Hamburg'WHERECustomerName='AlfredsFutterkiste'

UpdateWarning!Becarefulwhenupdatingrecords.WhathappensifwehadomittedtheWHEREclause,intheexampleabove,likethis:

UPDATECUSTOMERSETContactName='AlfredSchmidt',City='Hamburg';

Page 49: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

DELETETrytoWriteandExecutethefollowingQuery

DELETEFROMCUSTOMERWHERECustomerName='AlfredsFutterkiste'ANDContactName='MariaAnders'

Note!Itispossibletodeleteallrowsinatablewithoutdeletingthetable

DELETE*FROMCUSTOMER

Note!Becareful!AllDatawillbelost!!

Page 50: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

Congratulations!- YouarefinishedwiththeExample

Page 51: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

AdvancedSQLFeatures

Hans-PetterHalvorsen,M.Sc.

Views,StoredProcedures,TriggersandFunctions

https://www.youtube.com/watch?v=SHELF_iQUeU

Page 52: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

AdvancedSQLFeatures• Views:Viewsarevirtualtablesforeasieraccesstodata

storedinmultipletables.• StoredProcedures:AStoredProcedureisaprecompiled

collectionofSQLstatements.Inastoredprocedureyoucanuseifsentence,declarevariables,etc.

• Triggers:Adatabasetriggeriscodethatisautomaticallyexecutedinresponsetocertaineventsonaparticulartableinadatabase.

• Functions:WithSQLandSQLServeryoucanuselotsofbuilt-infunctionsoryoumaycreateyourownfunctions

Theory

Page 53: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

53

ItisassumedthatyoualreadyhavecreatedtheseTablesinaprevious task

Page 54: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

54

selectSchoolName,CourseNamefromSCHOOLinnerjoinCOURSEonSCHOOL.SchoolId =COURSE.SchoolId

Example:

YoulinkPrimaryKeysandForeignKeystogether

TrythisExample

GetDatafrommultiple tablesinasingleQueryusingJoins

Page 55: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

CreatingViewsusingSQLcodeIF EXISTS (SELECT name

FROM 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

YoucanUsetheViewasanordinary tableinQueries:

AViewisa“virtual”tablethatcancontaindatafrommultipletables

InsidetheViewyoujointhedifferent tablestogetherusingtheJOIN operator

TheNameoftheView

CreateView:

UsingtheView:

Thispartisnotnecessary– butifyoumakeanychanges,youneedtodeletetheoldversionbeforeyoucanupdateit

TrytoCreatethisViewandmakesureitworks

select * from CourseData

1

2

Page 56: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

CreatingViewsusingtheEditor

AddnecessarytablesSavetheView

GraphicalInterfacewhereyoucanselectcolumnsyouneed

TrythisExample

4

1

2

3

Page 57: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

StoredProcedureIFEXISTS (SELECTname

FROMsysobjectsWHEREname = 'StudentGrade'AND type= 'P')

DROPPROCEDUREStudentGradeOG

CREATEPROCEDUREStudentGrade@Studentvarchar(50),@Coursevarchar(10),@Gradevarchar(1)

AS

DECLARE@StudentId int,@CourseId int

select@StudentId =StudentIdfromSTUDENTwhereStudentName=@Student

select@CourseId =CourseId fromCOURSEwhereCourseName=@Course

insertintoGRADE(StudentId,CourseId,Grade)values (@StudentId,@CourseId,@Grade)GO

execute StudentGrade 'John Wayne', 'SCE2006', 'B'

AStoredProcedureislikeaMethodinC#- itisapieceofcodewithSQLcommandsthatdoaspecifictask– andyoureuseit

InputArgumentsInternal/LocalVariables

ProcedureName

SQLCode(the“body”oftheStoredProcedure)

Note!Eachvariablestartswith@

CreateStoredProcedure:

UsingtheStoredProcedure:

Thispartisnotnecessary– butifyoumakeanychanges,youneedtodeletetheoldversionbeforeyoucanupdateit

TrytoCreatethisStoredProcedureandmakesureitworks

1

2

Page 58: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

TriggerIF EXISTS (SELECT name

FROM 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,updateordeletedatainaTablespecified intheTrigger.

InsidetheTriggeryoucanuseordinarySQLstatements,createvariables,etc.

NameoftheTrigger

SpecifywhichTabletheTriggershallworkon

Internal/LocalVariables

SQLCode(The“body”oftheTrigger)

SpecifywhatkindofoperationstheTriggershallacton

Note!“INSERTED”isatemporarilytablecontainingthelatestinserteddata,anditisveryhandy touseinsideatrigger

CreatetheTrigger:

Thispartisnotnecessary– butifyoumakeanychanges,youneedtodeletetheoldversionbeforeyoucanupdateit

TrytoCreatethisTriggerandmakesureitworks

Page 59: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

Quiz

http://www.w3schools.com/quiztest/quiztest.asp?qtest=SQL

TestyourskillswiththisMultipleChoiceTest

Page 60: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

WanttolearnmoreSQL?

Page 61: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

Congratulations!- YouarefinishedwiththeExample

Page 62: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

DatabaseCommunicationinLabVIEWLabVIEW

Hans-PetterHalvorsen,M.Sc.

https://www.youtube.com/watch?v=q0_2zPtBbeE

Page 63: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

ODBCODBC(OpenDatabaseConnectivity) isastandardizedinterface(API)foraccessingthedatabasefromaclient.Youcanusethisstandardtocommunicatewithdatabasesfromdifferentvendors, suchasOracle,SQLServer,etc.ThedesignersofODBCaimedtomakeitindependent ofprogramming languages,databasesystems,andoperatingsystems.ControlPanel→AdministrativeTools→DataSources(ODBC)

WewillusethisODBCConnection laterinLabVIEWinordertoopentheDatabaseConnection fromLabVIEW

Theory

Note!Makesuretousethe32bit versionoftheODBCTool!

Page 64: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

ODBC– StepbyStepInstructions

64

TheNameofyourSQLServer

TheNameofyourODBCConnection

UseeitherWindowsorSQLServerauthentication(Windowsissimplesttouse!)

SelecttheDatabaseyouareusing

Testyourconnectiontoseeifitsworks

Page 65: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

SQLServerConfigurationManager

MakesuretoEnable theseProtocols!

IfnottheDatabaseCommunicationfromLabVIEWmaynotworkproperly!

Page 66: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

LabVIEWSQLToolkit

http://home.hit.no/~hansha/documents/labview/code/SQLToolkit.zip

ForEasyDatabaseCommunicationwithLabVIEW

©Hans-PetterHalvorsenDownloadforfreehere:

SoftwareSoftware

Page 67: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

LabVIEWSQLToolkit

67

Example1:GetDatafromDatabaseintoLabVIEW:

Example2:WriteDatatoDatabasefromLabVIEW:

EasyAccesstoDatabaseSystemsfromLabVIEW

YourODBCConnection

2DTablewithData

1

Query

Query

2 3

1 2 3

TrytheseExamples

Page 68: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

LabVIEWSQLToolkitEasyAccesstoDatabaseSystemsfromLabVIEW

AlternativeSolution:TypeintheConnectionStringforyourDatabase

Note!Whenusing thismethod,youdontneedtocreateanODBCConnection first!

YourPasswordforthesauser

YourSQLServerInstance

TypeyourDatabasehere

YourSQLQuery

Page 69: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

DatabaseCommunicationinLabVIEW

69

InthisExampleweusetheNITC-01Thermocoupledeviceinorder tologTemperaturedatatoaSQLServerDatabasefromLabVIEW.

Page 70: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

LabVIEWSQLToolkitExampleIfwewanttosaveinputdatafromtheuserwecanusethe“FormatIntoString”function

executeCreateBook ‘LordoftheRings',‘J.R.R.Tolkien',Wiley',‘32-2-333-56',Fantasy'

The%s operatorwillbereplacedbythetextfromtheTextBox ontheFrontPanel.ForNumberswecanuse%d (Integer)or%f forFloating-point Number.

ResultingSQLQuery:

GUI/HMI

Code:2

1

3

Page 71: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

LabVIEWExample MainProgram

Pop-upDialogBox

Page 72: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

SubVIforSavingDatatotheDatabase

SubVIforRetrievingDatafromtheDatabase

MainProgram

UpdateGUI

Page 73: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

VIPropertiesSettings

Page 74: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

VIPropertiesSettings

Page 75: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

Congratulations!- YouarefinishedwiththeExample

Page 76: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

DatabaseCommunicationinVisualStudio/C#VisualStudio

Hans-PetterHalvorsen,M.Sc.

Page 77: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

ASP.NETWebForm AppExample

ASP.NETisaWebFrameworkavailablefromVisualStudio.Easilyexplained,itisjusta“Template”forcreatingWebPagesusingC#

Page 78: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

Database

78

ThisisourExampleDatabase(DesignedwithERwin)

Page 79: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

79

SQLScript- Tablesif not exists (select * from dbo.sysobjects where id = object_id(N'[AUTHOR]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)CREATE TABLE [AUTHOR](

[AuthorId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,[AuthorName] [varchar](50) NOT NULL UNIQUE,[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'[PUBLISHER]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)CREATE TABLE [PUBLISHER](

[PublisherId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,[PublisherName] [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,[EMail] [varchar](50) NULL,

)GO

if not exists (select * from dbo.sysobjects where id = object_id(N'[CATEGORY]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)CREATE TABLE [CATEGORY](

[CategoryId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,[CategoryName] [varchar](50) NOT NULL UNIQUE,[Description] [varchar](1000) NULL,

)GO

if not exists (select * from dbo.sysobjects where id = object_id(N'[BOOK]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)CREATE TABLE [BOOK](

[BookId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,[Title] [varchar](50) NOT NULL UNIQUE,[ISBN] [varchar](20) NOT NULL,[PublisherId] [int] NOT NULL FOREIGN KEY REFERENCES [PUBLISHER] ([PublisherId]),[AuthorId] [int] NOT NULL FOREIGN KEY REFERENCES [AUTHOR] ([AuthorId]),[CategoryId] [int] NOT NULL FOREIGN KEY REFERENCES [CATEGORY] ([CategoryId]),[Description] [varchar](1000) NULL,[Year] [date] NULL,[Edition] [int] NULL,[AverageRating] [float] NULL,

)GO

Page 80: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

SQLScript– InsertsomeDataintotheTables--CATEGORY ----------------------------------INSERT INTO CATEGORY (CategoryName) VALUES ('Science')GOINSERT INTO CATEGORY (CategoryName) VALUES ('Programming')GOINSERT INTO CATEGORY (CategoryName) VALUES ('Novel')GO

--AUTHOR ----------------------------------INSERT INTO AUTHOR (AuthorName) VALUES ('Knut Hamsun')GOINSERT INTO AUTHOR (AuthorName) VALUES ('Gilbert Strang')GOINSERT INTO AUTHOR (AuthorName) VALUES ('J.R.R Tolkien')GOINSERT INTO AUTHOR (AuthorName) VALUES ('Dorf Bishop')GO

--PUBLISHER ----------------------------------INSERT INTO PUBLISHER (PublisherName) VALUES ('Prentice Hall')GOINSERT INTO PUBLISHER (PublisherName) VALUES ('Wiley')GOINSERT INTO PUBLISHER (PublisherName) VALUES ('McGraw-Hill')GO

Page 81: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

--BOOK ----------------------------------INSERT INTO BOOK (Title, ISBN, PublisherId, AuthorId, CategoryId) VALUES('Introduction to Linear Algebra','0-07-066781-0',(select PublisherId from PUBLISHER where PublisherName='Prentice Hall'),(select AuthorId from AUTHOR where AuthorName='Gilbert Strang'),(select CategoryId from CATEGORY where CategoryName='Science'))GO

INSERT INTO BOOK (Title, ISBN, PublisherId, AuthorId, CategoryId) VALUES('Modern Control System','1-08-890781-0',(select PublisherId from PUBLISHER where PublisherName='Wiley'),(select AuthorId from AUTHOR where AuthorName='Dorf Bishop'),(select CategoryId from CATEGORY where CategoryName='Programming'))GO

INSERT INTO BOOK (Title, ISBN, PublisherId, AuthorId, CategoryId) VALUES('The Lord of the Rings','2-09-066556-2',(select PublisherId from PUBLISHER where PublisherName='McGraw-Hill'),(select AuthorId from AUTHOR where AuthorName='J.R.R Tolkien'),(select CategoryId from CATEGORY where CategoryName='Novel'))GO

SQLScript– InsertsomeDataintotheTables

Page 82: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

ASP.NETWebFormCreateaNewProjectinVisualStudio

Page 83: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

83

AddaNewWebForm(“Books.aspx”)

Books.aspx

Right-clickintheSolutionsExplorerandselect“AddNewItem”

Page 84: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

CreatethefollowingGUI(“Books.aspx”)

GridView (DragandDropfromtheToolbox)

Header

Page 85: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

85

CreatethefollowingCode(“Books.aspx.cs”)using System.Web.Configuration;using DatabaseWebApp.Data;

...

public partial class BookList : System.Web.UI.Page{private string connectionString = WebConfigurationManager.ConnectionStrings["LibraryDBConnectionString"].ConnectionString;

void Page_Load(object sender, EventArgs e){

if (!IsPostBack){

FillBookGrid();}

}

private void FillBookGrid(){

List<Book> bookList = new List<Book>();Book book = new Book();

bookList = book.GetBooks(connectionString);

gridBookList.DataSource = bookList;gridBookList.DataBind();

}}

WeshallcreatetheConnectionString totheDatabaseinthe“Web.configpage”

ReferencetoourClassthatcommunicateswiththeDatabase

SeenextslidesforimplementationoftheBookClass

Note!!

Page 86: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

86

CreateDatabaseCode– CreateanewClass(“Books.cs”)

Books.cs

Page 87: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

87

CreatetheFollowingClassin“Books.cs”using System.Data.SqlClient;using System.Data.SqlTypes;using System.Data;

public class Book{

public int BookId { get; set; }public string Title { get; set; }public string Isbn { get; set; }public string PublisherName { get; set; }public string AuthorName { get; set; }public string CategoryName { get; set; }

public List<Book> GetBooks(string connectionString){

List<Book> bookList = new List<Book>();

SqlConnection con = new SqlConnection(connectionString);

string selectSQL = "select BookId, Title, Isbn, PublisherName, AuthorName, CategoryName from GetBookData";

con.Open();

SqlCommand cmd = new SqlCommand(selectSQL, con);

SqlDataReader dr = cmd.ExecuteReader();

if (dr != null){

while (dr.Read()){

Book book = new Book();

book.BookId = Convert.ToInt32(dr["BookId"]);book.Title = dr["Title"].ToString();book.Isbn = dr["ISBN"].ToString();book.PublisherName = dr["PublisherName"].ToString();book.AuthorName = dr["AuthorName"].ToString();book.CategoryName = dr["CategoryName"].ToString();

bookList.Add(book);}

}

return bookList;}

}

GetBookDataisaView(seenextslide)

Page 88: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

SQLScript– Views– “GetBookData”IF EXISTS (SELECT name

FROM sysobjectsWHERE name = 'GetBookData'AND type = 'V')

DROP VIEW GetBookDataGO

CREATE VIEW GetBookDataAS

SELECTBOOK.BookId,BOOK.Title,BOOK.ISBN,PUBLISHER.PublisherName,AUTHOR.AuthorName,CATEGORY.CategoryName

FROM BOOKINNER JOIN AUTHOR ON BOOK.AuthorId = AUTHOR.AuthorIdINNER JOIN PUBLISHER ON BOOK.PublisherId = PUBLISHER.PublisherIdINNER JOIN CATEGORY ON BOOK.CategoryId = CATEGORY.CategoryId

GO

Page 89: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

CreateDatabaseConnectionStringin“Web.config”<connectionStrings>

<add name="LibraryDBConnectionString"connectionString="Data Source=macwin8;Initial Catalog=BOOKS;Persist Security Info=True;User ID=sa;Password=xxx"providerName="System.Data.SqlClient" />

</connectionStrings>

Where“xxx”isyourSQLServerDatabasePassword

Finally,Runyourapplication:

Congratulations!Itworks!

YourDatabase

UserNameandPasswordforyourSQLServer

Page 90: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

Congratulations!- YouarefinishedwiththeExample

Page 91: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

TrytoCreateAdd,EditandDeleteaswell

StepbyStepGuide:http://home.hit.no/~hansha/documents/software/software_development/topics/resources/programming/exercises/Create%20Database%20WebForm%20App/Create%20Database%20WebForm%20App.pdf

Page 92: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

Congratulations!- YouarefinishedwiththeExample

Page 93: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

Congratulations!- Youarefinishedwithall theExamplesinthisTutorial

Page 94: Database Overview - halvorsen.blog › documents › technology › resources... · Microsoft SQL Server SQL Server consists of a Database Engine and a Management Studio. The Database

Hans-PetterHalvorsen,M.Sc.

UniversityCollegeofSoutheastNorwaywww.usn.no

E-mail:[email protected]:http://home.hit.no/~hansha/