Structured Query Language
Transcription
Structured Query Language
UniversityCollegeofSoutheastNorway StructuredQueryLanguage Hans-PetterHalvorsen,2016.01.08 TheTutorialisavailableOnline:http://home.hit.no/~hansha/?tutorial=sql http://home.hit.no/~hansha TableofContents 1 2 IntroductiontoSQL...........................................................................................................5 1.1 DataDefinitionLanguage(DDL)..................................................................................7 1.2 DataManipulationLanguage(DML)...........................................................................7 IntroductiontoSQLServer................................................................................................8 2.1 3 SQLServerManagementStudio.................................................................................9 2.1.1 CreateanewDatabase......................................................................................10 2.1.2 Queries..............................................................................................................11 CREATETABLE.................................................................................................................12 3.1 DatabaseModelling..................................................................................................14 3.2 CreateTablesusingtheDesignerTools....................................................................16 3.3 SQLConstraints.........................................................................................................16 3.3.1 PRIMARYKEY.....................................................................................................17 3.3.2 FOREIGNKEY.....................................................................................................18 3.3.3 NOTNULL/RequiredColumns.........................................................................21 3.3.4 UNIQUE.............................................................................................................22 3.3.5 CHECK................................................................................................................24 3.3.6 DEFAULT............................................................................................................26 3.3.7 AUTOINCREMENTorIDENTITY.........................................................................27 3.4 ALTERTABLE.............................................................................................................28 4 INSERTINTO....................................................................................................................30 5 UPDATE...........................................................................................................................32 2 3 TableofContents 6 DELETE.............................................................................................................................34 7 SELECT.............................................................................................................................36 7.1 TheORDERBYKeyword............................................................................................38 7.2 SELECTDISTINCT.......................................................................................................39 7.3 TheWHEREClause....................................................................................................39 7.3.1 Operators..........................................................................................................40 7.3.2 LIKEOperator....................................................................................................40 7.3.3 INOperator........................................................................................................41 7.3.4 BETWEENOperator...........................................................................................41 7.4 Wildcards..................................................................................................................41 7.5 AND&OROperators................................................................................................42 7.6 SELECTTOPClause....................................................................................................43 7.7 Alias..........................................................................................................................44 7.8 Joins..........................................................................................................................44 7.8.1 8 DifferentSQLJOINs...........................................................................................45 SQLScripts.......................................................................................................................47 8.1 UsingComments.......................................................................................................47 8.1.1 Single-linecomment..........................................................................................47 8.1.2 Multiple-linecomment......................................................................................47 8.2 Variables...................................................................................................................48 8.3 Built-inGlobalVariables...........................................................................................49 8.3.1 8.4 @@IDENTITY.....................................................................................................49 FlowControl.............................................................................................................50 8.4.1 IF–ELSE.............................................................................................................50 8.4.2 WHILE................................................................................................................51 8.4.3 CASE...................................................................................................................52 Tutorial:StructuredQueryLanguage(SQL) 4 8.4.4 9 TableofContents CURSOR.............................................................................................................53 Views...............................................................................................................................55 9.1 10 UsingtheGraphicalDesigner...................................................................................56 StoredProcedures........................................................................................................60 10.1 11 NOCOUNTON/NOCOUNTOFF..............................................................................63 Functions......................................................................................................................65 11.1 Built-inFunctions..................................................................................................65 11.1.1 StringFunctions.............................................................................................65 11.1.2 DateandTimeFunctions...............................................................................66 11.1.3 MathematicsandStatisticsFunctions...........................................................66 11.1.4 AVG()..............................................................................................................67 11.1.5 COUNT().........................................................................................................67 11.1.6 TheGROUPBYStatement..............................................................................68 11.1.7 TheHAVINGClause........................................................................................69 11.2 User-definedFunctions.........................................................................................70 12 Triggers.........................................................................................................................71 13 CommunicationfromotherApplications.....................................................................74 13.1 ODBC.....................................................................................................................74 13.2 MicrosoftExcel......................................................................................................75 14 References....................................................................................................................77 Tutorial:StructuredQueryLanguage(SQL) 1 IntroductiontoSQL SQL(StructuredQueryLanguage)isadatabasecomputerlanguagedesignedformanaging datainrelationaldatabasemanagementsystems(RDBMS). SQL,isastandardizedcomputerlanguagethatwasoriginallydevelopedbyIBMforquerying, alteringanddefiningrelationaldatabases,usingdeclarativestatements. SQLispronounced/ˌɛskjuːˈɛl/ (letterbyletter) or/ˈsiːkwəl/ (asaword). WhatcanSQLdo? • • • • • SQLcanexecutequeriesagainstadatabase SQLcanretrievedatafromadatabase SQLcaninsertrecordsinadatabase SQLcanupdaterecordsinadatabase SQLcandeleterecordsfromadatabase 5 6 • • • • • IntroductiontoSQL SQLcancreatenewdatabases SQLcancreatenewtablesinadatabase SQLcancreatestoredproceduresinadatabase SQLcancreateviewsinadatabase SQLcansetpermissionsontables,procedures,andviews EvenifSQLisastandard,manyofthedatabasesystemsthatexisttodayimplementtheir ownversionoftheSQLlanguage.InthisdocumentwewillusetheMicrosoftSQLServeras anexample. Therearelotsofdifferentdatabasesystems,orDBMS–DatabaseManagementSystems, suchas: • • • • • • • MicrosoftSQLServer o Enterprise,Developerversions,etc. o Expressversionisfreeofcharge Oracle MySQL(Oracle,previouslySunMicrosystems)-MySQLcanbeusedfreeofcharge (opensourcelicense),WebsitesthatuseMySQL:YouTube,Wikipedia,Facebook MicrosoftAccess IBMDB2 Sybase …lotsofothersystems InthisTutorialwewillfocusonMicrosoftSQLServer.SQLServerusesT-SQL(Transact-SQL). T-SQLisMicrosoft'sproprietaryextensiontoSQL.T-SQLisverysimilartostandardSQL,but inadditionitsupportssomeextrafunctionality,built-infunctions,etc. Tutorial:StructuredQueryLanguage(SQL) 7 IntroductiontoSQL OtherusefulTutorialsaboutdatabases: • • IntroductiontoDatabaseSystems DatabaseCommunicationinLabVIEW TheseTutorialsarelocatedat:http://home.hit.no/~hansha 1.1 DataDefinitionLanguage(DDL) TheDataDefinitionLanguage(DDL)managestableandindexstructure.Themostbasic itemsofDDLaretheCREATE,ALTER,RENAMEandDROPstatements: • • • CREATEcreatesanobject(atable,forexample)inthedatabase. DROPdeletesanobjectinthedatabase,usuallyirretrievably. ALTERmodifiesthestructureanexistingobjectinvariousways—forexample,adding acolumntoanexistingtable. 1.2 DataManipulationLanguage(DML) TheDataManipulationLanguage(DML)isthesubsetofSQLusedtoadd,updateanddelete data. TheacronymCRUDreferstoallofthemajorfunctionsthatneedtobeimplementedina relationaldatabaseapplicationtoconsideritcomplete.Eachletterintheacronymcanbe mappedtoastandardSQLstatement: Operation Create SQL INSERTINTO Read(Retrieve) Update Delete(Destroy) SELECT UPDATE DELETE Description insertsnewdataintoa database extractsdatafromadatabase updatesdatainadatabase deletesdatafromadatabase Tutorial:StructuredQueryLanguage(SQL) 2 IntroductiontoSQLServer MicrosoftisthevendorofSQLServer. WehavedifferenteditionsofSQLServer,whereSQLServerExpressisfreetodownloadand use. SQLServerusesT-SQL(Transact-SQL).T-SQLisMicrosoft'sproprietaryextensiontoSQL.TSQLisverysimilartostandardSQL,butinadditionitsupportssomeextrafunctionality,builtinfunctions,etc.T-SQLexpandsontheSQLstandardtoincludeproceduralprogramming, localvariables,varioussupportfunctionsforstringprocessing,dateprocessing, mathematics,etc. SQLServerconsistsofaDatabaseEngineandaManagementStudio(andlotsofotherstuff whichwewillnotmentionhere).TheDatabaseenginehasnographicalinterface-itisjusta servicerunninginthebackgroundofyourcomputer(preferableontheserver).The ManagementStudioisgraphicaltoolforconfiguringandviewingtheinformationinthe database.Itcanbeinstalledontheserverorontheclient(orboth). 8 9 IntroductiontoSQLServer 2.1 SQLServerManagementStudio SQLServerManagementStudioisaGUItoolincludedwithSQLServerforconfiguring, managing,andadministeringallcomponentswithinMicrosoftSQLServer.Thetoolincludes bothscripteditorsandgraphicaltoolsthatworkwithobjectsandfeaturesoftheserver.As mentionedearlier,versionofSQLServerManagementStudioisalsoavailableforSQLServer ExpressEdition,forwhichitisknownasSQLServerManagementStudioExpress. AcentralfeatureofSQLServerManagementStudioistheObjectExplorer,whichallowsthe usertobrowse,select,andactuponanyoftheobjectswithintheserver.Itcanbeusedto visuallyobserveandanalyzequeryplansandoptimizethedatabaseperformance,among others.SQLServerManagementStudiocanalsobeusedtocreateanewdatabase,alterany existingdatabaseschemabyaddingormodifyingtablesandindexes,oranalyze performance.ItincludesthequerywindowswhichprovideaGUIbasedinterfacetowrite andexecutequeries. WhencreatingSQLcommandsandqueries,the“QueryEditor”(select“NewQuery”from theToolbar)isused(showninthefigureabove). WithSQLandthe“QueryEditor”wecandoalmosteverythingwithcode,butsometimesitis alsoagoodideatousethedifferentDesignertoolsinSQLtohelpusdotheworkwithout coding(somuch). Tutorial:StructuredQueryLanguage(SQL) 10 2.1.1 IntroductiontoSQLServer CreateanewDatabase ItisquitesimpletocreateanewdatabaseinMicrosoftSQLServer.Justright-clickonthe “Databases”nodeandselect“NewDatabase…” Therearelotsofsettingsyoumaysetregardingyourdatabase,buttheonlyinformationyou mustfillinisthenameofyourdatabase: Tutorial:StructuredQueryLanguage(SQL) 11 IntroductiontoSQLServer YoumayalsousetheSQLlanguagetocreateanewdatabase,butsometimesitiseasierto justusethebuilt-infeaturesintheManagementStudio. 2.1.2 Queries InordertomakeanewSQLquery,selectthe“NewQuery”buttonfromtheToolbar. HerewecanwriteanykindofqueriesthatissupportedbytheSQLlanguage. Tutorial:StructuredQueryLanguage(SQL) 3 CREATETABLE Beforeyoustartimplementingyourtablesinthedatabase,youshouldalwaysspendsome timedesignyourtablesproperlyusingadesigntoollike,e.g.,ERwin,ToadDataModeler, PowerDesigner,Visio,etc.ThisiscalledDatabaseModeling. TheCREATETABLEstatementisusedtocreateatableinadatabase. Syntax: CREATE TABLE ( column_name1 column_name2 column_name3 .... ) table_name data_type, data_type, data_type, Thedatatypespecifieswhattypeofdatathecolumncanhold. 12 13 CREATETABLE Youhavespecialdatatypesfornumbers,textdates,etc. Examples: • • • • Numbers:int,float Text/Stings:varchar(X)–whereXisthelengthofthestring Dates:datetime etc. Example: Wewanttocreateatablecalled“CUSTOMER”whichhasthefollowingcolumnsanddata types: CREATE TABLE CUSTOMER ( CustomerId int IDENTITY(1,1) PRIMARY KEY, CustomerNumber int NOT NULL UNIQUE, LastName varchar(50) NOT NULL, FirstName varchar(50) NOT NULL, AreaCode int NULL, Address varchar(50) NULL, Phone varchar(50) NULL, ) GO Bestpractice: Whencreatingtablesyoushouldconsiderfollowingtheseguidelines: • • • Tables:Useuppercaseandsingularformintablenames–notplural,e.g., “STUDENT”(notstudents) Columns:UsePascalnotation,e.g.,“StudentId” PrimaryKey: o Ifthetablenameis“COURSE”,namethePrimaryKeycolumn“CourseId”,etc. Tutorial:StructuredQueryLanguage(SQL) 14 • • • • CREATETABLE o “Always”useIntegerandIdentity(1,1)forPrimaryKeys.UseUNIQUE constraintforothercolumnsthatneedstobeunique,e.g.RoomNumber SpecifyRequiredColumns(NOTNULL)–i.e.,whichcolumnsthatneedtohavedata ornot Standardizeonfew/theseDataTypes:int,float,varchar(x),datetime,bit UseEnglishfortableandcolumnnames Avoidabbreviations!(UseRoomNumber–notRoomNo,RoomNr,...) 3.1 DatabaseModelling Asmentioninthebeginningofthechapter,youshouldalwaysstartwithdatabasemodelling beforeyoustartimplementingthetablesinadatabasesystem. BelowweseeadatabasemodelincreatedwithERwin. Withthistoolwecantransferthedatabasemodelastablesintodifferentdatabasesystems, suchase.g.,SQLServer.CAERwinDataModelerCommunityEditionisfreewitha25objects limit.IthassupportforOracle,SQLServer,MySQL,ODBCandSybase. Tutorial:StructuredQueryLanguage(SQL) 15 CREATETABLE BelowweseethesametablesinsidethedesigntoolinSQLServer. Tutorial:StructuredQueryLanguage(SQL) 16 CREATETABLE 3.2 CreateTablesusingtheDesignerTools Evenifyoucando“everything”usingtheSQLlanguage,itissometimeseasiertodoitinthe designertoolsintheManagementStudioinSQLServer. Insteadofcreatingascriptyoumayaswelleasilyusethedesignerforcreatingtables. Step1:Select“NewTable…”: Step2:Next,thetabledesignerpopsupwhereyoucanaddcolumns,datatypes,etc. InthisdesignerwemayalsospecifyColumnNames,DataTypes,etc. Step3:SavethetablebyclickingtheSavebutton. 3.3 SQLConstraints Constraintsareusedtolimitthetypeofdatathatcangointoatable. Tutorial:StructuredQueryLanguage(SQL) 17 CREATETABLE Constraintscanbespecifiedwhenatableiscreated(withtheCREATETABLEstatement)or afterthetableiscreated(withtheALTERTABLEstatement). Herearethemostimportantconstraints: • • • • • • • PRIMARYKEY NOTNULL UNIQUE FOREIGNKEY CHECK DEFAULT IDENTITY Inthesectionsbelowwewillexplainsomeoftheseindetail. 3.3.1 PRIMARYKEY ThePRIMARYKEYconstraintuniquelyidentifieseachrecordinadatabasetable. Primarykeysmustcontainuniquevalues.Itisnormaltojustuserunningnumbers,like1,2, 3,4,5,…asvaluesinPrimaryKeycolumn.Itisagoodideatoletthesystemhandlethisfor youbyspecifyingthatthePrimaryKeyshouldbesettoidentity(1,1).IDENTITY(1,1)means thefirstvaluewillbe1andthenitwillincrementby1. Eachtableshouldhaveaprimarykey,andeachtablecanhaveonlyONEprimarykey. IfwetakeacloserlookattheCUSTOMERtablecreatedearlier: CREATE TABLE [CUSTOMER] ( CustomerId int IDENTITY(1,1) PRIMARY KEY, CustomerNumber int NOT NULL UNIQUE, LastName varchar(50) NOT NULL, FirstName varchar(50) NOT NULL, AreaCode int NULL, Address varchar(50) NULL, Phone varchar(50) NULL, ) GO Asyouseeweusethe“PrimaryKey”keywordtospecifythatacolumnshouldbethe PrimaryKey. Tutorial:StructuredQueryLanguage(SQL) 18 CREATETABLE SettingPrimaryKeysintheDesignerTools: IfyouusetheDesignertoolsinSQLServer,youcaneasilysettheprimaryKeyinatablejust byright-clickandselect“SetprimaryKey”. TheprimaryKeycolumnwillthenhaveasmallkey infronttoillustratethatthiscolumnis aPrimaryKey. 3.3.2 FOREIGNKEY AFOREIGNKEYinonetablepointstoaPRIMARYKEYinanothertable. Example: WewillcreateaCREATETABLEscriptforthesetables: Tutorial:StructuredQueryLanguage(SQL) 19 CREATETABLE SCHOOL: CREATE TABLE SCHOOL ( SchoolId int IDENTITY(1,1) 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 CLASS: CREATE TABLE CLASS ( ClassId int IDENTITY(1,1) PRIMARY KEY, SchoolId int NOT NULL FOREIGN KEY REFERENCES SCHOOL (SchoolId), ClassName varchar(50) NOT NULL UNIQUE, Description varchar(1000) NULL, ) GO TheFOREIGNKEYconstraintisusedtopreventactionsthatwoulddestroylinksbetween tables. TheFOREIGNKEYconstraintalsopreventsthatinvaliddatafrombeinginsertedintothe foreignkeycolumn,becauseithastobeoneofthevaluescontainedinthetableitpointsto. SettingForeignKeysintheDesignerTools: Ifyouwanttousethedesigner,right-clickonthecolumnthatyouwanttobetheForeign Keyandselect“Relationships…”: Tutorial:StructuredQueryLanguage(SQL) 20 CREATETABLE Thefollowingwindowpopsup(ForeignKeyRelationships): Clickonthe“Add”buttonandthenclickonthesmall“…”button.Thenthefollowingwindow popsup(TablesandColumns): Tutorial:StructuredQueryLanguage(SQL) 21 CREATETABLE HereyouspecifytheprimaryKeyColumninthePrimaryKeytableandtheForeignKey ColumnintheForeignKeytable. 3.3.3 NOTNULL/RequiredColumns TheNOTNULLconstraintenforcesacolumntoNOTacceptNULLvalues. TheNOTNULLconstraintenforcesafieldtoalwayscontainavalue.Thismeansthatyou cannotinsertanewrecord,orupdatearecordwithoutaddingavaluetothisfield. IfwetakeacloserlookattheCUSTOMERtablecreatedearlier: CREATE TABLE [CUSTOMER] ( CustomerId int IDENTITY(1,1) PRIMARY KEY, CustomerNumber int NOT NULL UNIQUE, LastName varchar(50) NOT NULL, FirstName varchar(50) NOT NULL, AreaCode int NULL, Address varchar(50) NULL, Phone varchar(50) NULL, ) GO Tutorial:StructuredQueryLanguage(SQL) 22 CREATETABLE Weseethat“CustomerNumber”,“LastName”and“FirstName”issetto“NOTNULL”,this meansthesecolumnsneedstocontaindata.While“AreaCode”,“Address”and“Phone”may beleftempty,i.e,theydon’tneedtofilledout. Note!AprimarykeycolumncannotcontainNULLvalues. SettingNULL/NOTNULLintheDesignerTools: IntheTableDesigneryoucaneasilysetwhichcolumnsthatshouldallowNULLornot: 3.3.4 UNIQUE TheUNIQUEconstraintuniquelyidentifieseachrecordinadatabasetable.TheUNIQUEand PRIMARYKEYconstraintsbothprovideaguaranteeforuniquenessforacolumnorsetof columns. APRIMARYKEYconstraintautomaticallyhasaUNIQUEconstraintdefinedonit. Note!YoucanhavemanyUNIQUEconstraintspertable,butonlyonePRIMARYKEY constraintpertable. IfwetakeacloserlookattheCUSTOMERtablecreatedearlier: CREATE TABLE [CUSTOMER] ( CustomerId int IDENTITY(1,1) PRIMARY KEY, CustomerNumber int NOT NULL UNIQUE, LastName varchar(50) NOT NULL, FirstName varchar(50) NOT NULL, AreaCode int NULL, Address varchar(50) NULL, Tutorial:StructuredQueryLanguage(SQL) 23 CREATETABLE Phone varchar(50) NULL, ) GO Weseethatthe“CustomerNumber”issettoUNIQUE,meaningeachcustomermusthavea uniqueCustomerNumber.Example: SettingUNIQUEintheDesignerTools: Ifyouwanttousethedesigner,right-clickonthecolumnthatyouwanttobeUNIQUEand select“Indexes/Keys…”: Thenclick“Add”andthensetthe“IsUnique”propertyto“Yes”: Tutorial:StructuredQueryLanguage(SQL) 24 CREATETABLE 3.3.5 CHECK TheCHECKconstraintisusedtolimitthevaluerangethatcanbeplacedinacolumn. IfyoudefineaCHECKconstraintonasinglecolumnitallowsonlycertainvaluesforthis column. IfyoudefineaCHECKconstraintonatableitcanlimitthevaluesincertaincolumnsbased onvaluesinothercolumnsintherow. Example: CREATE TABLE [CUSTOMER] ( CustomerId int IDENTITY(1,1) PRIMARY KEY, CustomerNumber int NOT NULL UNIQUE CHECK(CustomerNumber>0), LastName varchar(50) NOT NULL, FirstName varchar(50) NOT NULL, AreaCode int NULL, Address varchar(50) NULL, Phone varchar(50) NULL, ) GO Inthiscase,whenwetrytoinsertaCustomerNumberlessthanzerowewillgetanerror message. SettingCHECKconstraintsintheDesignerTools: Ifyouwanttousethedesigner,right-clickonthecolumnwhereyouwanttosetthe constraintsandselect“CheckConstraints…”: Tutorial:StructuredQueryLanguage(SQL) 25 CREATETABLE Thenclick“Add”andthenclick“…”inordertoopentheExpressionwindow: IntheExpressionwindowyoucantypeintheexpressionyouwanttouse: Tutorial:StructuredQueryLanguage(SQL) 26 CREATETABLE 3.3.6 DEFAULT TheDEFAULTconstraintisusedtoinsertadefaultvalueintoacolumn. Thedefaultvaluewillbeaddedtoallnewrecords,ifnoothervalueisspecified. Example: CREATE TABLE [CUSTOMER] ( CustomerId int IDENTITY(1,1) PRIMARY KEY, CustomerNumber int NOT NULL UNIQUE, LastName varchar(50) NOT NULL, FirstName varchar(50) NOT NULL, Country varchar(20) DEFAULT 'Norway', AreaCode int NULL, Address varchar(50) NULL, Phone varchar(50) NULL, ) GO SettingDEFAULTvaluesintheDesignerTools: Selectthecolumnandgointothe“ColumnProperties”: Tutorial:StructuredQueryLanguage(SQL) 27 3.3.7 CREATETABLE AUTOINCREMENTorIDENTITY Veryoftenwewouldlikethevalueoftheprimarykeyfieldtobecreatedautomaticallyevery timeanewrecordisinserted. Example: CREATE TABLE CUSTOMER ( CustomerId int IDENTITY(1,1) PRIMARY KEY, CustomerNumber int NOT NULL UNIQUE, LastName varchar(50) NOT NULL, FirstName varchar(50) NOT NULL, AreaCode int NULL, Address varchar(50) NULL, Phone varchar(50) NULL, ) GO Asshownbelow,weusetheIDENTITY()forthis.IDENTITY(1,1)meansthefirstvaluewillbe1 andthenitwillincrementby1. Settingidentity(1,1)intheDesignerTools: WecanusethedesignertoolstospecifythataPrimaryKeyshouldbeanidentitycolumn thatisautomaticallygeneratedbythesystemwhenweinsertdataintothetable. ClickonthecolumninthedesignerandgointotheColumnPropertieswindow: Tutorial:StructuredQueryLanguage(SQL) 28 CREATETABLE 3.4 ALTERTABLE TheALTERTABLEstatementisusedtoadd,delete,ormodifycolumnsinanexistingtable. Toaddacolumninatable,usethefollowingsyntax: ALTER TABLE table_name ADD column_name datatype Todeleteacolumninatable,usethefollowingsyntax(noticethatsomedatabasesystems don'tallowdeletingacolumn): ALTER TABLE table_name DROP COLUMN column_name Tochangethedatatypeofacolumninatable,usethefollowingsyntax: ALTER TABLE table_name ALTER COLUMN column_name datatype IfweuseCREATETABLEandthetablealreadyexistsinthetablewewillgetanerror message,soifwecombineCREATETABLEandALTERTABLEwecancreaterobustdatabase scriptsthatgivesnoerrors,astheexampleshownbelow: if not exists (select * from dbo.sysobjects where id = object_id(N'[CUSTOMER]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) CREATE TABLE CUSTOMER ( CustomerId int PRIMARY KEY, CustomerNumber int NOT NULL UNIQUE, LastName varchar(50) NOT NULL, FirstName varchar(50) NOT NULL, AreaCode int NULL, Address varchar(50) NULL, Phone varchar(50) NULL, ) GO if exists(select * from dbo.syscolumns where id = object_id(N'[CUSTOMER]') and OBJECTPROPERTY(id, N'IsUserTable') = 1 and name = 'CustomerId') ALTER TABLE CUSTOMER ALTER COLUMN CustomerId int Else ALTER TABLE CUSTOMER ADD CustomerId int GO if exists(select * from dbo.syscolumns where id = object_id(N'[CUSTOMER]') and OBJECTPROPERTY(id, N'IsUserTable') = 1 and name = 'CustomerNumber') ALTER TABLE CUSTOMER ALTER COLUMN CustomerNumber int Tutorial:StructuredQueryLanguage(SQL) 29 Else ALTER TABLE CUSTOMER ADD CustomerNumber int GO ... Tutorial:StructuredQueryLanguage(SQL) CREATETABLE 4 INSERTINTO TheINSERTINTOstatementisusedtoinsertanewrowinatable. ItispossibletowritetheINSERTINTOstatementintwoforms. Thefirstformdoesn'tspecifythecolumnnameswherethedatawillbeinserted,onlytheir values: INSERT INTO table_name VALUES (value1, value2, value3,...) Example: INSERT INTO CUSTOMER VALUES ('1000', 'Smith', 'John', 12, 'California', '11111111') Thesecondformspecifiesboththecolumnnamesandthevaluestobeinserted: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...) Thisformisrecommended! Example: INSERT INTO CUSTOMER (CustomerNumber, LastName, FirstName, AreaCode, Address, Phone) VALUES ('1000', 'Smith', 'John', 12, 'California', '11111111') InsertDataOnlyinSpecifiedColumns: Itisalsopossibletoonlyadddatainspecificcolumns. Example: INSERT INTO CUSTOMER (CustomerNumber, LastName, FirstName) VALUES ('1000', 'Smith', 'John') Note!YouneedatleasttoincludeallcolumnsthatcannotbeNULL. WerememberthetabledefinitionfortheCUSTOMERtable: 30 31 INSERTINTO i.e.,weneedtoincludeatleast“CustomerNumber”,“LastName”and“FirstName”. “CustomerId”issetto“identity(1,1)”andthereforevaluesforthiscolumnaregeneratedby thesystem. InsertDataintheDesignerTools: Whenyouhavecreatedthetablesyoucaneasilyinsertdataintothemusingthedesigner tools.Right-clickonthespecifictableandselect“EditTop200Rows”: Thenyoucanenterdatainatableformat,similarto,e.g.,MSExcel: Tutorial:StructuredQueryLanguage(SQL) 5 UPDATE TheUPDATEstatementisusedtoupdateexistingrecordsinatable. Thesyntaxisasfollows: UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value Note!NoticetheWHEREclauseintheUPDATEsyntax.TheWHEREclausespecifieswhich recordorrecordsthatshouldbeupdated.IfyouomittheWHEREclause,allrecordswillbe updated! Example: update CUSTOMER set AreaCode=46 where CustomerId=2 Beforeupdate: Afterupdate: Ifyoudon’tincludetheWHEREclausetheresultbecomes: →SomakesuretoincludetheWHEREclausewhenusingtheUPDATEcommand! 32 33 UPDATE UpdateDataintheDesignerTools: Thesamewayyouinsertdatayoucanalsoupdatethedata.Right-clickonthespecifictable andselect“EditTop200Rows”: Thenyoucanchangeyourdata: Tutorial:StructuredQueryLanguage(SQL) 6 DELETE TheDELETEstatementisusedtodeleterowsinatable. Syntax: DELETE FROM table_name WHERE some_column=some_value Note!NoticetheWHEREclauseintheDELETEsyntax.TheWHEREclausespecifieswhich recordorrecordsthatshouldbedeleted.IfyouomittheWHEREclause,allrecordswillbe deleted! Example: delete from CUSTOMER where CustomerId=2 Beforedelete: Afterdelete: DeleteAllRows: Itispossibletodeleteallrowsinatablewithoutdeletingthetable.Thismeansthatthe tablestructure,attributes,andindexeswillbeintact: DELETE FROM table_name Note!Makesuretodothisonlywhenyoureallymeanit!YoucannotUNDOthisstatement! DeleteDataintheDesignerTools: Youdeletedatainthedesignerbyright-clickontherowandselect“Delete”: 34 35 DELETE Tutorial:StructuredQueryLanguage(SQL) 7 SELECT TheSELECTstatementisprobablythemostusedSQLcommand.TheSELECTstatementis usedforretrievingrowsfromthedatabaseandenablestheselectionofoneormanyrowsor columnsfromoneormanytablesinthedatabase. WewillusetheCUSTOMERtableasanexample. TheCUSTOMERtablehasthefollowingcolumns: TheCUSTOMERtablecontainsthefollowingdata: Example: select * from CUSTOMER ThissimpleexamplegetsallthedatainthetableCUSTOMER.Thesymbol“*”isusedwhen youwanttogetallthecolumnsinthetable. 36 37 SELECT Ifyouonlywantafewcolumns,youmayspecifythenamesofthecolumnsyouwantto retrieve,example: select CustomerId, LastName, FirstName from CUSTOMER SointhesimplestformwecanusetheSELECTstatementasfollows: select <column_names> from <table_names> Ifwewantallcolumns,weusethesymbol“*” Note!SQLisnotcasesensitive.SELECTisthesameasselect. ThefullsyntaxoftheSELECTstatementiscomplex,butthemainclausescanbesummarized as: SELECT [ ALL | DISTINCT ] [TOP ( expression ) [PERCENT] [ WITH TIES ] ] select_list [ INTO new_table ] [ FROM table_source ] [ WHERE search_condition ] [ GROUP BY group_by_expression ] [ HAVING search_condition ] [ ORDER BY order_expression [ ASC | DESC ] ] Itseemscomplex,butwewilltakethedifferentpartsstepbystepinthenextsections. SelectDataintheDesignerTools: Right-clickonatableandselect“SelectTop1000Rows”: Thefollowingwillappear: Tutorial:StructuredQueryLanguage(SQL) 38 SELECT ASelectqueryisautomaticallycreatedforyouwhichyoucaneditifyouwantto. 7.1 TheORDERBYKeyword Ifyouwantthedatatoappearinaspecificorderyouneedtousethe“orderby”keyword. Example: select * from CUSTOMER order by LastName Youmayalsosortbyseveralcolumns,e.g.likethis: select * from CUSTOMER order by Address, LastName Ifyouusethe“orderby”keyword,thedefaultorderisascending(“asc”).Ifyouwantthe ordertobeopposite,i.e.,descending,thenyouneedtousethe“desc”keyword. Tutorial:StructuredQueryLanguage(SQL) 39 SELECT select * from CUSTOMER order by LastName desc 7.2 SELECTDISTINCT Inatable,someofthecolumnsmaycontainduplicatevalues.Thisisnotaproblem, however,sometimesyouwillwanttolistonlythedifferent(distinct)valuesinatable. TheDISTINCTkeywordcanbeusedtoreturnonlydistinct(different)values. Thesyntaxisasfollows: select distinct <column_names> from <table_names> Example: select distinct FirstName from CUSTOMER 7.3 TheWHEREClause TheWHEREclauseisusedtoextractonlythoserecordsthatfulfillaspecifiedcriterion. Thesyntaxisasfollows: select <column_names> from <table_name> where <column_name> operator value Example: select * from CUSTOMER where CustomerNumber='1001' Tutorial:StructuredQueryLanguage(SQL) 40 SELECT Note!SQLusessinglequotesaroundtextvalues,asshownintheexampleabove. 7.3.1 Operators WiththeWHEREclause,thefollowingoperatorscanbeused: Operator = <> > < >= <= BETWEEN LIKE IN Description Equal Notequal Greaterthan Lessthan Greaterthanorequal Lessthanorequal Betweenaninclusiverange Searchforapattern Ifyouknowtheexactvalueyouwanttoreturnforatleastoneofthe columns Examples: select * from CUSTOMER where AreaCode>30 7.3.2 LIKEOperator TheLIKEoperatorisusedtosearchforaspecifiedpatterninacolumn. Syntax: SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern Example: select * from CUSTOMER where LastName like 'J%' Note!The"%"signcanbeusedtodefinewildcards(missinglettersinthepattern)both beforeandafterthepattern. Tutorial:StructuredQueryLanguage(SQL) 41 SELECT select * from CUSTOMER where LastName like '%a%' YoumayalsocombinewiththeNOTkeyword,example: select * from CUSTOMER where LastName not like '%a%' 7.3.3 INOperator TheINoperatorallowsyoutospecifymultiplevaluesinaWHEREclause. Syntax: SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,...) 7.3.4 BETWEENOperator TheBETWEENoperatorselectsarangeofdatabetweentwovalues.Thevaluescanbe numbers,text,ordates. Syntax: SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2 7.4 Wildcards SQLwildcardscansubstituteforoneormorecharacterswhensearchingfordataina database. Note!SQLwildcardsmustbeusedwiththeSQLLIKEoperator. WithSQL,thefollowingwildcardscanbeused: Tutorial:StructuredQueryLanguage(SQL) 42 Wildcard % _ [charlist] [^charlist] or [!charlist] SELECT Description Asubstituteforzeroormorecharacters Asubstituteforexactlyonecharacter Anysinglecharacterincharlist Anysinglecharacternotincharlist Examples: SELECT * FROM CUSTOMER WHERE LastName LIKE 'J_cks_n' SELECT * FROM CUSTOMER WHERE CustomerNumber LIKE '[10]%' 7.5 AND&OROperators TheANDoperatordisplaysarecordifboththefirstconditionandthesecondconditionis true. TheORoperatordisplaysarecordifeitherthefirstconditionorthesecondconditionistrue. Examples: select * from CUSTOMER where LastName='Smith' and FirstName='John' select * from CUSTOMER where LastName='Smith' or FirstName='John' Tutorial:StructuredQueryLanguage(SQL) 43 SELECT CombiningAND&OR: YoucanalsocombineANDandOR(useparenthesistoformcomplexexpressions). Example: select * from CUSTOMER where LastName='Smith' and (FirstName='John' or FirstName='Smith') 7.6 SELECTTOPClause TheTOPclauseisusedtospecifythenumberofrecordstoreturn. TheTOPclausecanbeveryusefulonlargetableswiththousandsofrecords.Returninga largenumberofrecordscanimpactonperformance. Syntax: SELECT TOP number|percent column_name(s) FROM table_name Examples: select TOP 1 * from CUSTOMER Youcanalsospecifyinpercent: select TOP 60 percent * from CUSTOMER Thisisveryusefulforlargetableswiththousandsofrecords Tutorial:StructuredQueryLanguage(SQL) 44 SELECT 7.7 Alias Youcangiveatableoracolumnanothernamebyusinganalias.Thiscanbeagoodthingto doifyouhaveverylongorcomplextablenamesorcolumnnames. Analiasnamecouldbeanything,butusuallyitisshort. SQLAliasSyntaxforTables: SELECT column_name(s) FROM table_name AS alias_name SQLAliasSyntaxforColumns: SELECT column_name AS alias_name FROM table_name 7.8 Joins SQLjoinsareusedtoquerydatafromtwoormoretables,basedonarelationshipbetween certaincolumnsinthesetables. Tutorial:StructuredQueryLanguage(SQL) 45 SELECT 7.8.1 DifferentSQLJOINs Beforewecontinuewithexamples,wewilllistthetypesofJOINyoucanuse,andthe differencesbetweenthem. • • • • JOIN:Returnrowswhenthereisatleastonematchinbothtables LEFTJOIN:Returnallrowsfromthelefttable,eveniftherearenomatchesinthe righttable RIGHTJOIN:Returnallrowsfromtherighttable,eveniftherearenomatchesinthe lefttable FULLJOIN:Returnrowswhenthereisamatchinoneofthetables Example: Given2tables: • • SCHOOL CLASS Tutorial:StructuredQueryLanguage(SQL) 46 SELECT Thediagramisshownbelow: Wewanttogetthefollowinginformationusingaquery: SchoolName ClassName … … … … InordertogetinformationfrommorethanonetableweneedtousetheJOIN.TheJOINis usedtojointheprimarykeyinonetablewiththeforeignkeyinanothertable. select SCHOOL.SchoolName, CLASS.ClassName from SCHOOL INNER JOIN CLASS ON SCHOOL.SchoolId = CLASS.SchoolId Tutorial:StructuredQueryLanguage(SQL) 8 SQLScripts ASQLscriptisacollectionofSQLstatementsthatyoucanexecuteinoneoperation.Youcan useanykindofSQLcommands,suchasinsert,select,delete,update,etc.Inadditionyou candefineandusevariables,andyoumayalsouseprogramflowlikeIf-Else,etc.Youmay alsoaddcommentstomakethescripteasiertoreadandunderstand. 8.1 UsingComments UsingcommentsinyouSQLscriptisimportanttomakethescripteasiertoreadand understand. InSQLwecanuse2differentkindsofcomments: • • Single-linecomment Multiple-linecomment 8.1.1 Single-linecomment Wecancommentonelineatthetimeusing“--”beforethetextyouwanttocommentout. Syntax: -- text_of_comment 8.1.2 Multiple-linecomment Wecancommentseverallineusing“/*”inthestartofthecommentand“*/”intheendof thecomment. Syntax: /* text_of_comment text_of_comment */ 47 48 SQLScripts 8.2 Variables TheabilitytousingvariablesinSQLisapowerfulfeature.Youneedtousethekeyword DECLAREwhenyouwanttodefinethevariables.Localvariablesmusthavethethesymbol “@”asaprefix.Youalsoneedtospecifyadatatypeforyourvariable(int,varchar(x),etc.). Syntaxfordeclaringvariables: declare @local_variable data_type Ifyouhavemorethanonevariableyouwanttodeclare: declare @myvariable1 data_type, @myvariable2 data_type, … Whenyouwanttoassignvaluestothevariable,youmustuseeitheraSEToraSELECT statement. Example: declare @myvariable int set @myvariable=4 Ifyouwanttoseethevalueforavariable,youcane.g.,usethePRINTcommandlikethis: declare @myvariable int set @myvariable=4 print @myvariable ThefollowingwillbeshowninSQLServer: AssigningvariableswithavaluefromaSELECTstatementisveryuseful. Tutorial:StructuredQueryLanguage(SQL) 49 SQLScripts WeusetheCUSTOMERtableasanexample: Youcanassignavaluetothevariablefromaselectstatementlikethis: declare @mylastname varchar(50) select @mylastname=LastName from CUSTOMER where CustomerId=2 print @mylastname YoucanalsouseavariableintheWHEREclauseLIKE,e.g.,this: declare @find varchar(30) set @find = 'J%' select * from CUSTOMER where LastName LIKE @find 8.3 Built-inGlobalVariables SQLhavelotsofbuilt-invariablesthatareveryusefultouseinqueriesandscripts. 8.3.1 @@IDENTITY AfteranINSERT,SELECTINTO,orbulkcopystatementiscompleted,@@IDENTITYcontains thelastidentityvaluethatisgeneratedbythestatement.Ifthestatementdidnotaffectany tableswithidentitycolumns,@@IDENTITYreturnsNULL.Ifmultiplerowsareinserted, generatingmultipleidentityvalues,@@IDENTITYreturnsthelastidentityvaluegenerated. Example: Giventotables;SCHOOLandCOURSE: Tutorial:StructuredQueryLanguage(SQL) 50 SQLScripts SCHOOLtable: COURSEtable: WewanttoinsertanewSchoolintotheSCHOOLtableandwewanttoinsert2newCourses intheCOURSEtablethatbelongtotheSchoolweinsert.Tofindthe“SchoolId”wecanuse the@@IDENTITYvariable: declare @SchoolId int -- Insert Data into SCHOOL table insert into SCHOOL(SchoolName) values ('MIT') select @SchoolId = @@IDENTITY -- Insert Courses for the specific School above in the COURSE table insert into COURSE(SchoolId,CourseName) values (@SchoolId, 'MIT101') insert into COURSE(SchoolId,CourseName) values (@SchoolId, 'MIT201') Theresultbecomes: SCHOOLtable: COURSEtable: 8.4 FlowControl Aswithotherprogramminglanguagesyoucanusedifferentkindofflowcontrol,suchasIFELSE,WHILE,etc,whichisveryuseful. 8.4.1 IF–ELSE TheIF-ELSEisveryuseful.Belowweseeanexample: declare @customerNumber int Tutorial:StructuredQueryLanguage(SQL) 51 SQLScripts select @customerNumber=CustomerNumber from CUSTOMER where CustomerId=2 if @customerNumber > 1000 print 'The Customer Number is larger than 1000' else print 'The Customer Number is not larger than 1000' BEGIN…END: IfmorethanonelineofcodeistobeexecutedwithinanIFsentenceyouneedtouse BEGIN…END. Example: select @customerNumber=CustomerNumber from CUSTOMER where CustomerId=2 if @customerNumber > 1000 begin print 'The Customer Number is larger than 1000' update CUSTOMER set AreaCode=46 where CustomerId=2 end else print 'The Customer Number is not larger than 1000' 8.4.2 WHILE WecanalsouseWHILE,whichisknownfromotherprogramminglanguages. Example: WeareusingtheCUSTOMERtable: andthefollowingquery: while (select AreaCode from CUSTOMER where CustomerId=1) < 20 begin update CUSTOMER set AreaCode = AreaCode + 1 Tutorial:StructuredQueryLanguage(SQL) 52 SQLScripts end select * from CUSTOMER AsyoucanseethecodeinsidetheWHILEloopisexecutedaslongas“AreaCode”for CustomerId=1islessthan20.Foreachiterationisthe“AreaCode”forthatcustomer incrementedwith1. 8.4.3 CASE TheCASEstatementevaluatesalistofconditionsandreturnsoneofmultiplepossibleresult expressions. Example: Wehavea“GRADE”tablethatcontainsthegradesforeachstudentindifferentcourses: select GradeId, StudentId, CourseId, Grade from GRADE Inthe“GRADE”tableisthegradesstoredasnumbers,butsincethestudentsgetgradeswith thelettersA..F(A=5,B=4,C=3,D=2,E=1,F=0),wewanttoconvertthevaluesinthetable intolettersusingaCASEstatement: select GradeId, StudentId, CourseId, case Grade when 5 then when 4 then when 3 then when 2 then when 1 then when 0 then else '-' end as Grade from 'A' 'B' 'C' 'D' 'E' 'F' Tutorial:StructuredQueryLanguage(SQL) 53 SQLScripts GRADE 8.4.4 CURSOR Inadvancesscripts,CURSORsmaybeveryuseful.ACURSORworkslikeanadvancedWHILE loopwhichweusetoiteratethroughtherecordsinoneormoretables. CURSORSareusedmainlyinstoredprocedures,triggers,andSQLscripts. Example: WeusetheCUSTOMERtableasanexample: WewillcreateaCURSORthatiteratethroughalltherecordsintheCUSTOMERtableand checkifthePhonenumberconsistsof8digits,ifnotthescriptwillreplacetheinvalidPhone numberwiththetext“Phonenumberisnotvalid”. HereistheSQLScriptusingaCURSOR: DECLARE @CustomerId int, @phone varchar(50) DECLARE db_cursor CURSOR FOR SELECT CustomerId from CUSTOMER OPEN db_cursor FETCH NEXT FROM db_cursor INTO @CustomerId WHILE @@FETCH_STATUS = 0 BEGIN select @phone=Phone from CUSTOMER where CustomerId=@CustomerId if LEN(@phone) < 8 Tutorial:StructuredQueryLanguage(SQL) 54 SQLScripts update CUSTOMER set Phone='Phone number is not valid' where CustomerId=@CustomerId FETCH NEXT FROM db_cursor INTO @CustomerId END CLOSE db_cursor DEALLOCATE db_cursor TheCUSTOMERtablebecomes: CreatingandusingaCURSORincludesthesesteps: • • • • • DeclareSQLvariablestocontainthedatareturnedbythecursor.Declareone variableforeachresultsetcolumn. AssociateaSQLcursorwithaSELECTstatementusingtheDECLARECURSOR statement.TheDECLARECURSORstatementalsodefinesthecharacteristicsofthe cursor,suchasthecursornameandwhetherthecursorisread-onlyorforward-only. UsetheOPENstatementtoexecutetheSELECTstatementandpopulatethecursor. UsetheFETCHINTOstatementtofetchindividualrowsandhavethedataforeach columnmovedintoaspecifiedvariable.OtherSQLstatementscanthenreference thosevariablestoaccessthefetcheddatavalues. Whenyouarefinishedwiththecursor,usetheCLOSEstatement.Closingacursor freessomeresources,suchasthecursor'sresultsetanditslocksonthecurrentrow. TheDEALLOCATEstatementcompletelyfreesallresourcesallocatedtothecursor, includingthecursorname. Tutorial:StructuredQueryLanguage(SQL) 9 Views Viewsarevirtualtableforeasieraccesstodatastoredinmultipletables. SyntaxforcreatingaView: CREATE VIEW <ViewName> AS … ...butitmightbeeasiertodoitinthegraphicalviewdesignerthatarebuiltintoSQL ManagementStudio. SyntaxforusingaView: select * from <MyView> where … Asshownabove,weuseaVIEWjustlikeweuseanordinarytable. 55 56 Views Example: WeusetheSCHOOLandCLASStablesasanexampleforourView.WewanttocreateaView thatlistsalltheexistingschoolsandthebelongingclasses. WecreatetheVIEWusingtheCREATEVIEWcommand: CREATE VIEW SchoolView AS SELECT SCHOOL.SchoolName, CLASS.ClassName FROM SCHOOL INNER JOIN CLASS ON SCHOOL.SchoolId = CLASS.SchoolId Note!Inordertogetinformationfrommorethanonetable,weneedtolinkthetables togetherusingaJOIN. 9.1 UsingtheGraphicalDesigner WecreatethesameViewusingthegraphicaldesignerinSQLServerManagementStudio: Tutorial:StructuredQueryLanguage(SQL) 57 Views Step1:Right-clickontheViewnodeandselect“NewView…”: Step2:Addnecessarytables: Tutorial:StructuredQueryLanguage(SQL) 58 Views Step3:AddColumns,etc. Step4:SavetheVIEW: Tutorial:StructuredQueryLanguage(SQL) 59 Step5:UsetheVIEWinaquery: select * from SchoolView Tutorial:StructuredQueryLanguage(SQL) Views 10 StoredProcedures AStoredProcedureisaprecompiledcollectionofSQLstatements.Inastoredprocedureyou canuseifsentence,declarevariables,etc. SyntaxforcreatingaStoredProcedure: CREATE PROCEDURE <ProcedureName> @<Parameter1> <datatype> … declare @myVariable <datatype> … Create your Code here Note!Youneedtousethesymbol“@”beforevariablenames. SyntaxforusingaStoredProcedure: EXECUTE <ProcedureName(…)> Example: 60 61 StoredProcedures WeusetheSCHOOLandCLASStablesasanexampleforourStoredProcedure.Wewantto createaStoredProcedurethatlistsalltheexistingschoolsandthebelongingclasses. WecreatetheStoredProcedureasfollows: CREATE PROCEDURE GetAllSchoolClasses AS select SCHOOL.SchoolName, CLASS.ClassName from SCHOOL inner join CLASS on SCHOOL.SchoolId = CLASS.SchoolId order by SchoolName, ClassName WhenwehavecreatedtheStoredProcedurewecanrun(orexecute)theStoredprocedure usingtheexecutecommandlikethis: execute GetAllSchoolClasses WecanalsocreateaStoreProcedurewithinputparameters. Example: Tutorial:StructuredQueryLanguage(SQL) 62 StoredProcedures Weusethesametablesinthisexample(SCHOOLandCLASS)butnowwewanttolistall classesforaspecificschool. TheStoredProcedurebecomes: CREATE PROCEDURE GetSpecificSchoolClasses @SchoolName varchar(50) AS select SCHOOL.SchoolName, CLASS.ClassName from SCHOOL inner join CLASS on SCHOOL.SchoolId = CLASS.SchoolId where SchoolName=@SchoolName order by ClassName Werun(orexecute)theStoredProcedure: execute GetSpecificSchoolClasses 'TUC' or: execute GetSpecificSchoolClasses 'NTNU' WhenwetrytocreateaStoredProcedurethatalreadyexistswegetthefollowingerror message: There is already an object named 'GetSpecificSchoolClasses' in the database. Thenwefirstneedtodelete(orDROP)theoldStoredProcedurebeforewecanrecreateit again. WecandothismanuallyintheManagementStudioinSQLlikethis: Tutorial:StructuredQueryLanguage(SQL) 63 StoredProcedures Abettersolutionistoaddcodeforthisinourscript,likethis: IF EXISTS (SELECT name FROM sysobjects WHERE name = GetSpecificSchoolClasses ' AND type = 'P') DROP PROCEDURE GetSpecificSchoolClasses GO CREATE PROCEDURE GetSpecificSchoolClasses @SchoolName varchar(50) AS select SCHOOL.SchoolName, CLASS.ClassName from SCHOOL inner join CLASS on SCHOOL.SchoolId = CLASS.SchoolId where SchoolName=@SchoolName order by ClassName SoweuseCREATEPROCEDUREtocreateaStoredProcedureandweuseDROPPROCEDURE todeleteaStoredProcedure. 10.1 NOCOUNTON/NOCOUNTOFF InadvancedStoredProceduresandScript,performanceisveryimportant.UsingSET NOCOUNTONandSETNOCOUNTOFFmakestheStoredProcedurerunfaster. SETNOCOUNTONstopsthemessagethatshowsthecountofthenumberofrowsaffected byaTransact-SQLstatementorstoredprocedurefrombeingreturnedaspartoftheresult set. Tutorial:StructuredQueryLanguage(SQL) 64 StoredProcedures SETNOCOUNTONpreventsthesendingofDONE_IN_PROCmessagestotheclientforeach statementinastoredprocedure.Forstoredproceduresthatcontainseveralstatementsthat donotreturnmuchactualdata,orforproceduresthatcontainTransact-SQLloops,setting SETNOCOUNTtoONcanprovideasignificantperformanceboost,becausenetworktrafficis greatlyreduced. Example: IF EXISTS (SELECT name FROM sysobjects WHERE name = 'sp_LIMS_IMPORT_REAGENT' AND type = 'P') DROP PROCEDURE sp_LIMS_IMPORT_REAGENT GO CREATE PROCEDURE sp_LIMS_IMPORT_REAGENT @Name varchar(100), @LotNumber varchar(100), @ProductNumber varchar(100), @Manufacturer varchar(100) AS SET NOCOUNT ON if not exists (SELECT ReagentId FROM LIMS_REAGENTS WHERE [Name]=@Name) INSERT INTO LIMS_REAGENTS ([Name], ProductNumber, Manufacturer) VALUES (@Name, @ProductNumber, @Manufacturer) else UPDATE LIMS_REAGENTS SET [Name] = @Name, ProductNumber = @ProductNumber, Manufacturer = @Manufacturer, WHERE [Name] = @Name SET NOCOUNT OFF GO ThisStoredProcedureupdatesatableinthedatabaseandinthiscaseyoudon’tnormally needfeedback,spsettingSETNOCOUNTONatthetopinthestoredprocedureisagood idea.itisalsogoodpracticetoSETNOCOUNTOFFatthebottomofthestoredprocedure. Tutorial:StructuredQueryLanguage(SQL) 11 Functions WithSQLandSQLServeryoucanuselotsofbuilt-infunctionsoryoumaycreateyourown functions.Herewewilllearntousesomeofthemostusedbuilt-infunctionsandinaddition wewillcreateourownfunction. 11.1 Built-inFunctions SQLhasmanybuilt-infunctionsforperformingcalculationsondata. Wehave2categoriesoffunctions,namelyaggregatefunctionsandscalarfunctions. Aggregatefunctionsreturnasinglevalue,calculatedfromvaluesinacolumn,whilescalar functionsreturnasinglevalue,basedontheinputvalue. Aggregatefunctions-examples: • • • • • • • AVG()-Returnstheaveragevalue STDEV()-Returnsthestandarddeviationvalue COUNT()-Returnsthenumberofrows MAX()-Returnsthelargestvalue MIN()-Returnsthesmallestvalue SUM()-Returnsthesum etc. Scalarfunctions-examples: • • • • • • UPPER()-Convertsafieldtouppercase LOWER()-Convertsafieldtolowercase LEN()-Returnsthelengthofatextfield ROUND()-Roundsanumericfieldtothenumberofdecimalsspecified GETDATE()-Returnsthecurrentsystemdateandtime etc. 11.1.1 StringFunctions HerearesomeusefulfunctionsusedtomanipulatewithstringsinSQLServer: 65 66 • • • • • • • • • • • • CHAR CHARINDEX REPLACE SUBSTRING LEN REVERSE LEFT RIGHT LOWER UPPER LTRIM RTRIM ReadmoreaboutthesefunctionsintheSQLServerHelp. 11.1.2 DateandTimeFunctions HerearesomeusefulDateandTimefunctionsinSQLServer: • • • • • • • • DATEPART GETDATE DATEADD DATEDIFF DAY MONTH YEAR ISDATE ReadmoreaboutthesefunctionsintheSQLServerHelp. 11.1.3 MathematicsandStatisticsFunctions HerearesomeusefulfunctionsformathematicsandstatisticsinSQLServer: • • • • • • • COUNT MIN,MAX COS,SIN,TAN SQRT STDEV MEAN AVG Tutorial:StructuredQueryLanguage(SQL) Functions 67 Functions ReadmoreaboutthesefunctionsintheSQLServerHelp. 11.1.4 AVG() TheAVG()functionreturnstheaveragevalueofanumericcolumn. Syntax: SELECT AVG(column_name) FROM table_name Example: GivenaGRADEtable: Wewanttofindtheaveragegradeforaspecificstudent: select AVG(Grade) as AvgGrade from GRADE where StudentId=1 11.1.5 COUNT() TheCOUNT()functionreturnsthenumberofrowsthatmatchesaspecifiedcriteria. TheCOUNT(column_name)functionreturnsthenumberofvalues(NULLvalueswillnotbe counted)ofthespecifiedcolumn: SELECT COUNT(column_name) FROM table_name TheCOUNT(*)functionreturnsthenumberofrecordsinatable: SELECT COUNT(*) FROM table_name Tutorial:StructuredQueryLanguage(SQL) 68 Functions WeusetheCUSTOMERtableasanexample: select COUNT(*) as NumbersofCustomers from CUSTOMER 11.1.6 TheGROUPBYStatement AggregatefunctionsoftenneedanaddedGROUPBYstatement. TheGROUPBYstatementisusedinconjunctionwiththeaggregatefunctionstogroupthe result-setbyoneormorecolumns. Syntax SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name Example: WeusetheCUSTOMERtableasanexample: Ifwetrythefollowing: select FirstName, MAX(AreaCode) from CUSTOMER Wegetthefollowingerrormessage: Column 'CUSTOMER.FirstName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. ThesolutionistousetheGROUPBY: select FirstName, MAX(AreaCode) from CUSTOMER group by FirstName Tutorial:StructuredQueryLanguage(SQL) 69 Functions 11.1.7 TheHAVINGClause TheHAVINGclausewasaddedtoSQLbecausetheWHEREkeywordcouldnotbeusedwith aggregatefunctions. Syntax: SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value WeusetheGRADEtableasanexample: select * from GRADE FirstweusetheGROUPBYstatement: select CourseId, AVG(Grade) from GRADE group by CourseId Whilethefollowingquery: select CourseId, AVG(Grade) from GRADE group by CourseId having AVG(Grade)>3 Tutorial:StructuredQueryLanguage(SQL) 70 11.2 Functions User-definedFunctions INSQLwemayalsocreateourownfunctions,so-calleduser-definedfunctions. Auser-definedfunctionisaroutinethatacceptsparameters,performsanaction,suchasa complexcalculation,andreturnstheresultofthatactionasavalue.Thereturnvaluecan eitherbeascalar(single)valueoratable.Usethisstatementtocreateareusableroutine thatcanbeusedinotherqueries. InSQLdatabases,auser-definedfunctionprovidesamechanismforextendingthe functionalityofthedatabaseserverbyaddingafunctionthatcanbeevaluatedinSQL statements.TheSQLstandarddistinguishesbetweenscalarandtablefunctions.Ascalar functionreturnsonlyasinglevalue(orNULL),whereasatablefunctionreturnsa(relational) tablecomprisingzeroormorerows,eachrowwithoneormorecolumns. StoredProceduresvs.Functions: • • • • • • • Onlyfunctionscanreturnavalue(usingtheRETURNkeyword). StoredprocedurescanuseRETURNkeywordbutwithoutanyvaluebeingpassed[1] FunctionscouldbeusedinSELECTstatements,providedtheydon’tdoanydata manipulationandalsoshouldnothaveanyOUTorINOUTparameters. Functionsmustreturnavalue,butforstoredproceduresthisisnotcompulsory. AfunctioncanhaveonlyINparameters,whilestoredproceduresmayhaveOUTorIN OUTparameters. Afunctionisasubprogramwrittentoperformcertaincomputationsandreturna singlevalue. Astoredprocedureisasubprogramwrittentoperformasetofactions,andcan returnmultiplevaluesusingtheOUTparameterorreturnnovalueatall. User-definedfunctionsinSQLaredeclaredusingtheCREATEFUNCTIONstatement. Whenwehavecreatedthefunction,wecanusethefunctionthesamewayweusebuilt-in functions. Tutorial:StructuredQueryLanguage(SQL) 12 Triggers Adatabasetriggeriscodethatisautomaticallyexecutedinresponsetocertaineventsona particulartableinadatabase. SyntaxforcreatingaTrigger: CREATE TRIGGER <TriggerName> on <TableName> FOR INSERT, UPDATE, DELETE AS … Create your Code here GO TheTriggerwillautomaticallybeexecutedwhendataisinserted,updatedordeletedinthe tableasspecifiedintheTriggerheader. INSERTEDandDELETED: Insidetriggerswecanusetwospecialtables:theDELETEDtableandtheINSERTEDtables. SQLServerautomaticallycreatesandmanagesthesetables.Youcanusethesetemporary, 71 72 Triggers memory-residenttablestotesttheeffectsofcertaindatamodifications.Youcannotmodify thedatainthesetables. TheDELETEDtablestorescopiesoftheaffectedrowsduringDELETEandUPDATE statements.DuringtheexecutionofaDELETEorUPDATEstatement,rowsaredeletedfrom thetriggertableandtransferredtotheDELETEDtable. TheINSERTEDtablestorescopiesoftheaffectedrowsduringINSERTandUPDATE statements.Duringaninsertorupdatetransaction,newrowsareaddedtoboththe INSERTEDtableandthetriggertable.TherowsintheINSERTEDtablearecopiesofthenew rowsinthetriggertable. Example: WewillusetheCUSTOMERtableasanexample: WewillcreateaTRIGGERthatwillcheckifthePhonenumberisvalidwhenweinsertor updatedataintheCUSTOMERtable.Thevalidationcheckwillbeverysimple,i.e.,wewill checkifthePhonenumberislessthan8digits(whichisnormallengthinNorway).Ifthe Phonenumberislessthan8digits,thefollowingmessage“PhoneNumberisnotvalid”be writteninplaceofthewrongnumberinthePhonecolumn. TheTRIGGERbecomessomethinglikethis: IF EXISTS (SELECT name FROM sysobjects WHERE name = 'CheckPhoneNumber' AND type = 'TR') DROP TRIGGER CheckPhoneNumber GO CREATE TRIGGER CheckPhoneNumber ON CUSTOMER FOR UPDATE, INSERT AS DECLARE @CustomerId int, @Phone varchar(50), @Message varchar(50) set nocount on select @CustomerId = CustomerId from INSERTED select @Phone = Phone from INSERTED Tutorial:StructuredQueryLanguage(SQL) 73 Triggers set @Message = 'Phone Number ' + @Phone + ' is not valid' if len(@Phone) < 8 --Check if Phone Number have less than 8 digits update CUSTOMER set Phone = @Message where CustomerId = @CustomerId set nocount off GO WetesttheTRIGGERwiththefollowingINSERTINTOstatement: INSERT INTO CUSTOMER (CustomerNumber, LastName, FirstName, AreaCode, Address, Phone) VALUES ('1003', 'Obama', 'Barak', 51, 'Nevada', '4444') Theresultsbecome: Asyoucansee,theTRIGGERworksasexpected. WetrytoupdatethePhonenumbertoavalidnumber: update CUSTOMER set Phone = '44444444' where CustomerNumber = '1003' Theresultsbecome: Tutorial:StructuredQueryLanguage(SQL) 13 Communicationfrom otherApplications ADatabaseisastructuredwaytostorelotsofinformation.Theinformationisstoredin differenttables.“Everything”todayisstoredindatabases. Examples: • • • Bank/Accountsystems InformationinWebpagessuchasFacebook,Wikipedia,YouTube …lotsofotherexamples Thismeansweneedtobeabletocommunicatewiththedatabasefromotherapplications andprogramminglanguagesinordertoinsert,updateorretrievedatafromthedatabase. 13.1 ODBC ODBC(OpenDatabaseConnectivity)isastandardizedinterface(API)foraccessingthe databasefromaclient.Youcanusethisstandardtocommunicatewithdatabasesfrom differentvendors,suchasOracle,SQLServer,etc.ThedesignersofODBCaimedtomakeit independentofprogramminglanguages,databasesystems,andoperatingsystems. WewillusetheODBCDataSourceAdministrator: 74 75 CommunicationfromotherApplications 13.2 MicrosoftExcel MicrosoftExcelhastheabilitytoretrievedatafromdifferentdatasources,including differentdatabasesystems.ItisverysimpletoretrievedatafromSQLServerintoExcelsince ExcelandSQLServerhasthesamevendor(Microsoft). Tutorial:StructuredQueryLanguage(SQL) 76 CommunicationfromotherApplications Tutorial:StructuredQueryLanguage(SQL) 14 References MyBloghttp://home.hit.no/~hansha MicrosoftofficialSQLServerWebsite-http://www.microsoft.com/sqlserver SQLServerBooksOnline-http://msdn.microsoft.com/en-us/library/ms166020.aspx SQLServerHelp w3shools.com-http://www.w3schools.com/sql Wikipedia–MicrosoftSQLServer-http://en.wikipedia.org/wiki/Microsoft_SQL_Server Wikipedia-SQL-http://en.wikipedia.org/wiki/SQL Wikipedia–TransactSQL-http://en.wikipedia.org/wiki/T-SQL 77 Hans-PetterHalvorsen,M.Sc. E-mail:[email protected] Blog:http://home.hit.no/~hansha UniversityCollegeofSoutheastNorway www.usn.no