Download SQL Server and SQL

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

DBase wikipedia , lookup

Concurrency control wikipedia , lookup

Tandem Computers wikipedia , lookup

Functional Database Model wikipedia , lookup

Relational algebra wikipedia , lookup

Oracle Database wikipedia , lookup

Team Foundation Server wikipedia , lookup

Btrieve wikipedia , lookup

Microsoft Access wikipedia , lookup

Database wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Ingres (database) wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Clusterpoint wikipedia , lookup

Null (SQL) wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Database model wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Relational model wikipedia , lookup

SQL wikipedia , lookup

PL/SQL wikipedia , lookup

Transcript
SQLServerandSQL
StructuredQueryLanguage
StepbystepExercises
Hans-PetterHalvorsen
Database
Systems
Hans-PetterHalvorsen,M.Sc.
DatabaseSystems
ADatabaseisastructuredwaytostorelotsof
information.Theinformationisstoredindifferent
tables.
- “Everything”todayisstoredindatabases!
Examples:
• Bank/Accountsystems
• InformationinWebpagessuchasFacebook,
Wikipedia,YouTube,etc.
• Fronter,TimeEdit,etc.
• …lotsofotherexamples!
3
DatabaseManagementSystems(DBMS)
• MicrosoftSQLServer
– Enterprise,Developerversions,etc.(Professionaluse)
– Expressversionisfreeofcharge
• Oracle
• MySQL (ownedbyOracle,butpreviouslyownedbySun
Microsystems)- MySQLcanbeusedfreeofcharge(open
sourcelicense),WebsitesthatuseMySQL:YouTube,
Wikipedia,Facebook
• MicrosoftAccess
• IBMDB2
• Sybase
• etc.
WewilluseSQLserverbecauseitisverypopularintheindustrytoday,andwecanuseitfor
freeviatheMicrosoftDreamSparkPremiumSubscription – whichisavailableforthe
studentsandstaffatTelemarkUniversityCollege,orusetheExpressversionwhichisavailable
forfreeforeverybody.
4
MicrosoftSQLServer
SQLServerconsistsofaDatabaseEngineandaManagementStudio.TheDatabaseEnginehasnographicalinterface- it
isjustaservicerunninginthebackgroundofyourcomputer(preferableontheserver).TheManagementStudiois
graphicaltoolforconfiguringandviewingtheinformationinthedatabase.Itcanbeinstalledontheserveroronthe
client(orboth).
ThenewestversionofMicrosoftSQL
Serveris“SQLServer2014”
5
DatabaseDesign
6
DatabaseDesign– ERDiagram
ERDiagram(Entity-RelationshipDiagram)
• UsedforDesignandModelingofDatabases.
• SpecifyTablesandrelationship betweenthem(PrimaryKeysand
ForeignKeys)
TableName
Example:
TableName
Column
Names
PrimaryKey
PrimaryKey
ForeignKey
RelationalDatabase.InarelationaldatabaseallthetableshaveoneormorerelationwitheachotherusingPrimaryKeys
7
(PK)andForeignKeys(FK).Note!YoucanonlyhaveonePKinatable,butyoumayhaveseveralFK’s.
TableName
TableName
Column
Names
PrimaryKey
PrimaryKey
ForeignKey
8
Database- “BestPractice”
• Tables:Useuppercaseandsingular formintablenames– not
plural,e.g.,“STUDENT”(not“students”)
• Columns:UsePascalnotation,e.g.,“StudentId”
• PrimaryKey:
• Ifthetablenameis“COURSE”,namethePrimaryKeycolumn
“CourseId”,etc.
• “Always”useInteger andIdentity(1,1) forPrimaryKeys.Use
UNIQUEconstraintforothercolumnsthatneedstobeunique,
e.g.“RoomNumber”
• SpecifyRequired Columns(NOTNULL)– i.e.,whichcolumnsthat
needtohavedataornot
• Standardizeonfew/theseDataTypes:int,float,varchar(x),
datetime,bit
• UseEnglishfortableandcolumnnames
• Avoidabbreviations!(Use“RoomNumber”– not“RoomNo”,
“RoomNr”,...)
9
DatabaseDesignExercise
Students:CreatethisExample
usingERwin.
CreatetheTablesinSQLServer.
10
SQLServer
Hans-PetterHalvorsen,M.Sc.
MicrosoftSQLServer– CreateaNewDatabase
2
1
Nameyoudatabase,e.g.,
WEATHER_SYSTEM
12
MicrosoftSQLServer
3
YourSQLServer
4
1
2
WriteyourQueryhere
YourDatabase
Your
Tables
5
TheresultfromyourQuery
13
MicrosoftSQLServer
Doyougetanerror
whentryingto
changeyourtables?
Makesuretouncheck
thisoption!
14
CreateTablesusingtheDesignerTools
inSQLServer
Evenifyoucando“everything”usingtheSQLlanguage,itissometimeseasiertodo
somethinginthedesignertoolsintheManagementStudioinSQLServer.
Insteadofcreatingascriptyoumayaswelleasilyusethedesignerforcreatingtables,
constraints,insertingdata,etc.
1
Select“NewTable…”:
2
Next,thetabledesignerpopsupwhereyou
canaddcolumns,datatypes,etc.
Inthisdesignerwemayalsospecifyconstraints,suchas
primarykeys,unique,foreignkeys,etc.
15
CreateTableswiththe“DatabaseDiagram”
2
1
Youmayselect
existingtablesor
createnewTables
CreateNewTable
3
5
4
EnterColumns,selectDataTypes,
PrimaryKeys,etc.
16
SQL
StructuredQueryLanguage
Hans-PetterHalvorsen,M.Sc.
WhatisSQL
• SQL– StructuredQueryLanguage
• SQLisastandardlanguageforaccessing
databases.
18
SQL– StructuredQueryLanguage
QueryExamples:
• 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
Wehave4differentQueryTypes:INSERT,SELECT,UPDATEand DELETE
19
ImportantSQLCommands
•
•
•
•
•
•
•
•
•
•
•
SELECT- extractsdatafromadatabase
UPDATE- updatesdatainadatabase
DELETE- deletesdatafromadatabase
INSERTINTO- insertsnewdataintoadatabase
CREATEDATABASE- createsanewdatabase
ALTERDATABASE- modifiesadatabase
CREATETABLE- createsanewtable
ALTERTABLE- modifiesatable
DROPTABLE- deletesatable
CREATEINDEX- createsanindex(searchkey)
DROPINDEX- deletesanindex
20
SQL
StructuredQueryLanguage(SQL)
DML
DDL
DataDefinitionLanguage(DDL)
DataManipulationLanguage(DML)
CRUD
Create
Drop
CREATETables
DELETETables
Rename
RENAMETables
Alter
ALTERTables
Create
INSERTINTO
Read
SELECT
Update
UPDATE
Delete
DELETE
CreateTablesusingSQL
Example:
CREATE 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
...
...
22
SQLQueries
TableName:CUSTOMER
Students:CreatethefollowingTableandDatausingSQL
23
INSERT
Example:
INSERTINTOCustomers(CustomerName,ContactName,Address,City,PostalCode,Country)
VALUES('Cardinal','TomB.Erichsen','Skagen21','Stavanger','4006','Norway');
24
SELECT
Students:WriteandExecutethefollowingQueries.
SELECT*FROMCUSTOMER
SQLisNOTcasesensitive:selectisthesameasSELECT
SELECTCustomerName,CityFROMCUSTOMER
SELECTDISTINCTCityFROMCUSTOMER
SELECT*FROMCUSTOMERWHERECountry='Mexico'
SELECT*FROMCUSTOMERWHERECustomerID=1
SELECT*FROMCUSTOMERWHERECountry='Germany’ANDCity='Berlin'
SELECT*FROMCUSTOMERWHERECity='Berlin’ORCity='München'
SELECT*FROMCUSTOMERORDERBYCountry
SELECT*FROMCUSTOMERORDERBYCountryDESC
25
UPDATE
Students:WriteandExecutethefollowingQueries.
UPDATECUSTOMER
SETContactName='AlfredSchmidt',City='Hamburg'
WHERECustomerName='AlfredsFutterkiste'
UpdateWarning!
Becarefulwhenupdatingrecords.Whathappensifwehad
omittedtheWHEREclause,intheexampleabove,likethis:
UPDATECUSTOMER
SETContactName='AlfredSchmidt',City='Hamburg';
26
DELETE
Students:WriteandExecutethefollowingQueries.
DELETEFROMCUSTOMER
WHERECustomerName='AlfredsFutterkiste'
ANDContactName='MariaAnders'
Itispossibletodeleteallrowsinatablewithoutdeletingthetable
DELETE*FROMCUSTOMER
27
SQLQueries
Students:CreatetheTablesshownaboveusingSQL
Students:InsertsomeDataintotheTablesusingSQL
28
SELECT
Students:GetalldatafromtheBOOKtableusingSQL
29
AdvancedSQLFeatures
• Views:Viewsarevirtualtableforeasieraccessto
datastoredinmultipletables.
• StoredProcedures:AStoredProcedureisa
precompiledcollectionofSQLstatements.Ina
storedprocedureyoucanuseifsentence,declare
variables,etc.
• Triggers:Adatabasetriggeriscodethatis
automaticallyexecutedinresponsetocertain
eventsonaparticulartableinadatabase.
• Functions:WithSQLandSQLServeryoucanuse
lotsofbuilt-infunctionsoryoumaycreateyour
ownfunctions
30
GetDatafrommultiple tablesina
singleQueryusingJoins
Example:
Students:TrythisExample
select
SchoolName,
CourseName
from
YoulinkPrimaryKeysandForeignKeystogether
SCHOOL
innerjoinCOURSEonSCHOOL.SchoolId =COURSE.SchoolId
31
CreateView:
CreatingViewsusingSQL
AViewisa“virtual”tablethat
cancontaindatafrommultiple
tables
IF EXISTS (SELECT name
FROM
sysobjects
WHERE name = 'CourseData'
AND
type = 'V')
DROP VIEW CourseData
GO
Thispartisnotnecessary– butifyoumakeany
changes,youneedtodeletetheoldversionbefore
youcanupdateit
CREATE VIEW CourseData
AS
SELECT
SCHOOL.SchoolId,
SCHOOL.SchoolName,
COURSE.CourseId,
COURSE.CourseName,
COURSE.Description
TheNameoftheView
FROM
SCHOOL
INNER JOIN COURSE ON SCHOOL.SchoolId = COURSE.SchoolId
GO
UsingtheView:
select * from CourseData
InsidetheViewyoujointhe
differenttablestogetherusing
theJOIN operator
Students:CreatethisViewandmakesureitworks
YoucanUsetheViewasan
ordinarytableinQueries:
32
CreatingViewsusingtheEditor
3
GraphicalInterfacewhereyoucanselectcolumnsyouneed
1
2
4
Addnecessarytables
SavetheView
33
CreateStoredProcedure:
StoredProcedure
IFEXISTS(SELECTname
FROMsysobjects
WHEREname ='StudentGrade'
AND
type='P')
DROPPROCEDUREStudentGrade
OG
AStoredProcedureislikeMethodinC#
- itisapieceofcodewithSQL
commandsthatdoaspecifictask– and
youreuseit
CREATEPROCEDUREStudentGrade
@Studentvarchar(50),
@Coursevarchar(10),
@Gradevarchar(1)
Thispartisnotnecessary– butifyoumakeany
changes,youneedtodeletetheoldversionbefore
youcanupdateit
ProcedureName
AS
InputArguments
DECLARE
@StudentId int,
@CourseId int
Internal/LocalVariables
Note!Eachvariablestartswith@
selectStudentIdfromSTUDENTwhereStudentName =@Student
selectCourseId fromCOURSEwhereCourseName =@Course
insertintoGRADE(StudentId,CourseId,Grade)
values (@StudentId,@CourseId,@Grade)
GO
SQLCode(the“body”ofthe
StoredProcedure)
Students:CreatethisStoredProcedureandmake
sureitworks
UsingtheStoredProcedure:
execute StudentGrade 'John Wayne', 'SCE2006', 'B'
34
Trigger
ATriggerisexecutedwhenyouinsert,updateordeletedatainaTablespecifiedin
theTrigger.
Thispartisnotnecessary– butifyoumakeany
changes,youneedtodeletetheoldversionbefore
youcanupdateit
CreatetheTrigger:
IF EXISTS (SELECT name
FROM
sysobjects
WHERE name = 'CalcAvgGrade'
AND
type = 'TR')
DROP TRIGGER CalgAvgGrade
GO
NameoftheTrigger
SpecifywhichTablethe
Triggershallworkon
SpecifywhatkindofoperationstheTrigger
shallacton
CREATE TRIGGER CalcAvgGrade ON GRADE
FOR UPDATE, INSERT, DELETE
AS
DECLARE
@StudentId int,
@AvgGrade float
Internal/LocalVariables
select @StudentId = StudentId from INSERTED
select @AvgGrade = AVG(Grade) from GRADE where StudentId = @StudentId
update STUDENT set TotalGrade = @AvgGrade where StudentId = @StudentId
GO
Insidethe
Triggeryoucan
useordinarySQL
statements,
createvariables,
etc.
SQLCode
(The“body”
oftheTrigger)
Students:CreatethisTriggerandmakesureitworks
Note!“INSERTED”isatemporarilytablecontainingthelatestinserteddata,anditisvery
handytouseinsideatrigger
35
Quiz
TestyourskillswiththisMultiplechoiceTest
http://www.w3schools.com/quiztest/quiztest.asp?qtest=SQL
36
SQLTutorial
37
CreateTablesusingSQL
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
...
...
Students:CreatethenecessaryTablesinSQLServer(eitherwithaSQL
ScriptorusetheDesignerToolsinSQLServer)
38
References
•
•
•
•
•
•
H.-P.Halvorsen.(2014).StructuredQueryLanguage.Available:
http://home.hit.no/~hansha/?tutorial=sql
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
39
40
Hans-PetterHalvorsen,M.Sc.
UniversityCollegeofSoutheastNorway
www.usn.no
E-mail:[email protected]
Blog:http://home.hit.no/~hansha/