1 lnLroducLlon Lo SCL SCL (SLrucLured Cuery Language) ls a daLabase compuLer language deslgned for managlng daLa ln relaLlonal daLabase managemenL sysLems (8u8MS). SCL, ls a sLandardlzed compuLer language LhaL was orlglnally developed by l8M for querylng, alLerlng and deflnlng relaLlonal daLabases, uslng declaraLlve sLaLemenLs. SCL ls pronounced /!"s kju# $"l/ (leLLer by leLLer) or /$si#kw!l/ (as a word).
WhaL can SCL do? SCL can execuLe querles agalnsL a daLabase SCL can reLrleve daLa from a daLabase SCL can lnserL records ln a daLabase SCL can updaLe records ln a daLabase SCL can deleLe records from a daLabase 6 lnLroducLlon Lo SCL 1uLorlal: SLrucLured Cuery Language (SCL) SCL can creaLe new daLabases SCL can creaLe new Lables ln a daLabase SCL can creaLe sLored procedures ln a daLabase SCL can creaLe vlews ln a daLabase SCL can seL permlsslons on Lables, procedures, and vlews Lven lf SCL ls a sLandard, many of Lhe daLabase sysLems LhaL exlsL Loday lmplemenL Lhelr own verslon of Lhe SCL language. ln Lhls documenL we wlll use Lhe MlcrosofL SCL Server as an example. 1here are loLs of dlfferenL daLabase sysLems, or u8MS - uaLabase ManagemenL SysLems, such as: M|crosoft SL Server o LnLerprlse, ueveloper verslons, eLc. o Lxpress verslon ls free of charge Crac|e MySL (Cracle, prevlously Sun MlcrosysLems) - MySCL can be used free of charge (open source llcense), Web slLes LhaL use MySCL: ?ou1ube, Wlklpedla, lacebook M|crosoft Access I8M D82 Sybase . loLs of oLher sysLems
ln Lhls 1uLorlal we wlll focus on MlcrosofL SCL Server. SCL Server uses 1-SCL (1ransacL-SCL). 1-SCL ls MlcrosofL's proprleLary exLenslon Lo SCL. 1-SCL ls very slmllar Lo sLandard SCL, buL ln addlLlon lL supporLs some exLra funcLlonallLy, bullL-ln funcLlons, eLc. 7 lnLroducLlon Lo SCL 1uLorlal: SLrucLured Cuery Language (SCL) CLher useful 1uLorlals abouL daLabases: Introduct|on to Database Systems Database Commun|cat|on |n LabVILW 1hese 1uLorlals are locaLed aL: http:]]home.h|t.no]~hansha 1.1 uaLa ueflnlLlon Language (uuL) 1he Data Def|n|t|on Language (DDL) manages Lable and lndex sLrucLure. 1he mosL baslc lLems of uuL are Lhe C8LA1L, AL1L8, 8LnAML and u8C sLaLemenLs: CkLA1L creaLes an ob[ecL (a Lable, for example) ln Lhe daLabase. DkC deleLes an ob[ecL ln Lhe daLabase, usually lrreLrlevably. AL1Lk modlfles Lhe sLrucLure an exlsLlng ob[ecL ln varlous ways-for example, addlng a column Lo an exlsLlng Lable. 1.2 uaLa ManlpulaLlon Language (uML) 1he Data Man|pu|at|on Language (DML) ls Lhe subseL of SCL used Lo add, updaLe and deleLe daLa. 1he acronym CkUD refers Lo all of Lhe ma[or funcLlons LhaL need Lo be lmplemenLed ln a relaLlonal daLabase appllcaLlon Lo conslder lL compleLe. Lach leLLer ln Lhe acronym can be mapped Lo a sLandard SCL sLaLemenL: Cperat|on SL Descr|pt|on CreaLe lnSL81 ln1C lnserLs new daLa lnLo a daLabase kead (8eLrleve) SLLLC1 exLracLs daLa from a daLabase UpdaLe uuA1L updaLes daLa ln a daLabase DeleLe (uesLroy) uLLL1L deleLes daLa from a daLabase
8
2 lnLroducLlon Lo SCL Server MlcrosofL ls Lhe vendor of SCL Server. 1he newesL verslon ls SCL Server 2012". We have dlfferenL edlLlons of SCL Server, where SCL Server Lxpress ls free Lo download and use. SCL Server uses 1-SCL (1ransacL-SCL). 1-SCL ls MlcrosofL's proprleLary exLenslon Lo SCL. 1-SCL ls very slmllar Lo sLandard SCL, buL ln addlLlon lL supporLs some exLra funcLlonallLy, bullL-ln funcLlons, eLc. 1-SCL expands on Lhe SCL sLandard Lo lnclude procedural programmlng, local varlables, varlous supporL funcLlons for sLrlng processlng, daLe processlng, maLhemaLlcs, eLc. SCL Server conslsLs of a Database Lng|ne and a Management Stud|o (and loLs of oLher sLuff whlch we wlll noL menLlon here). 1he uaLabase englne has no graphlcal lnLerface - lL ls [usL a servlce runnlng ln Lhe background of your compuLer (preferable on Lhe server). 1he ManagemenL SLudlo ls graphlcal Lool for conflgurlng and vlewlng Lhe lnformaLlon ln Lhe daLabase. lL can be lnsLalled on Lhe server or on Lhe cllenL (or boLh).
9 lnLroducLlon Lo SCL Server 1uLorlal: SLrucLured Cuery Language (SCL) 2.1 SCL Server ManagemenL SLudlo SCL Server ManagemenL SLudlo ls a Cul Lool lncluded wlLh SCL Server for conflgurlng, managlng, and admlnlsLerlng all componenLs wlLhln MlcrosofL SCL Server. 1he Lool lncludes boLh scrlpL edlLors and graphlcal Lools LhaL work wlLh ob[ecLs and feaLures of Lhe server. As menLloned earller, verslon of SCL Server ManagemenL SLudlo ls also avallable for SCL Server Lxpress LdlLlon, for whlch lL ls known as SCL Server ManagemenL SLudlo Lxpress. A cenLral feaLure of SCL Server ManagemenL SLudlo ls Lhe Cb[ecL Lxplorer, whlch allows Lhe user Lo browse, selecL, and acL upon any of Lhe ob[ecLs wlLhln Lhe server. lL can be used Lo vlsually observe and analyze query plans and opLlmlze Lhe daLabase performance, among oLhers. SCL Server ManagemenL SLudlo can also be used Lo creaLe a new daLabase, alLer any exlsLlng daLabase schema by addlng or modlfylng Lables and lndexes, or analyze performance. lL lncludes Lhe query wlndows whlch provlde a Cul based lnLerface Lo wrlLe and execuLe querles.
When creaLlng SCL commands and querles, Lhe Cuery LdlLor" (selecL new Cuery" from Lhe 1oolbar) ls used (shown ln Lhe flgure above). WlLh SCL and Lhe Cuery LdlLor" we can do almosL everyLhlng wlLh code, buL someLlmes lL ls also a good ldea Lo use Lhe dlfferenL ueslgner Lools ln SCL Lo help us do Lhe work wlLhouL codlng (so much). 10 lnLroducLlon Lo SCL Server 1uLorlal: SLrucLured Cuery Language (SCL) 2.1.1 CreaLe a new uaLabase lL ls qulLe slmple Lo creaLe a new daLabase ln MlcrosofL SCL Server. !usL rlghL-cllck on Lhe uaLabases" node and selecL new uaLabase."
1here are loLs of seLLlngs you may seL regardlng your daLabase, buL Lhe only lnformaLlon you musL flll ln ls Lhe name of your daLabase:
11 lnLroducLlon Lo SCL Server 1uLorlal: SLrucLured Cuery Language (SCL) ?ou may also use Lhe SCL language Lo creaLe a new daLabase, buL someLlmes lL ls easler Lo [usL use Lhe bullL-ln feaLures ln Lhe ManagemenL SLudlo. 2.1.2 Cuerles ln order Lo make a new SCL query, selecL Lhe new Cuery" buLLon from Lhe 1oolbar.
Pere we can wrlLe any klnd of querles LhaL ls supporLed by Lhe SCL language.
12
3 C8LA1L 1A8LL 8efore you sLarL lmplemenLlng your Lables ln Lhe daLabase, you should always spend some Llme deslgn your Lables properly uslng a deslgn Lool llke, e.g., L8wln, 1oad uaLa Modeler, owerueslgner, vlslo, eLc. 1hls ls called uaLabase Modellng.
1he CkLA1L 1A8LL sLaLemenL ls used Lo creaLe a Lable ln a daLabase. SynLax: CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, .... ) 1he daLa Lype speclfles whaL Lype of daLa Lhe column can hold. 13 C8LA1L 1A8LL 1uLorlal: SLrucLured Cuery Language (SCL) ?ou have speclal daLa Lypes for numbers, LexL daLes, eLc. Lxamples: numbers: |nt, f|oat 1exL/SLlngs: varchar(k) - where x ls Lhe lengLh of Lhe sLrlng uaLes: datet|me eLc. Lxamp|e: We wanL Lo creaLe a Lable called CuS1CML8" whlch has Lhe followlng columns and daLa Lypes:
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
8est pract|ce: When creaLlng Lables you should conslder followlng Lhese guldellnes: 1ables: use upper case and slngular form ln Lable names - noL plural, e.g., S1uuLn1" (noL sLudenLs) Columns: use ascal noLaLlon, e.g., SLudenLld" rlmary key: o lf Lhe Lable name ls CCu8SL", name Lhe rlmary key column Courseld", eLc. 14 C8LA1L 1A8LL 1uLorlal: SLrucLured Cuery Language (SCL) o Always" use lnLeger and ldenLlLy(1,1) for rlmary keys. use unlCuL consLralnL for oLher columns LhaL needs Lo be unlque, e.g. 8oomnumber Speclfy 8equlred Columns (nC1 nuLL) - l.e., whlch columns LhaL need Lo have daLa or noL SLandardlze on few/Lhese uaLa 1ypes: lnL, floaL, varchar(x), daLeLlme, blL use Lngllsh for Lable and column names Avold abbrevlaLlons! (use 8oomnumber - noL 8oomno, 8oomnr, ...) 3.1 uaLabase Modelllng As menLlon ln Lhe beglnnlng of Lhe chapLer, you should always sLarL wlLh daLabase modelllng before you sLarL lmplemenLlng Lhe Lables ln a daLabase syLem. 8elow we see a daLabase model ln creaLed wlLh L8wln.
WlLh Lhls Lool we can Lransfer Lhe daLabase model as Lables lnLo dlfferenL daLabase sysLems, such as e.g., SCL Server. CA L8wln uaLa Modeler CommunlLy LdlLlon ls free wlLh a 23 ob[ecLs llmlL. lL has supporL for Cracle, SCL Server, MySCL, Cu8C and Sybase.
13 C8LA1L 1A8LL 1uLorlal: SLrucLured Cuery Language (SCL) 8elow we see Lhe same Lables lnslde Lhe deslgn Lool ln SCL Server.
16 C8LA1L 1A8LL 1uLorlal: SLrucLured Cuery Language (SCL) 3.2 CreaLe 1ables uslng Lhe ueslgner 1ools Lven lf you can do everyLhlng" uslng Lhe SCL language, lL ls someLlmes easler Lo do lL ln Lhe deslgner Lools ln Lhe ManagemenL SLudlo ln SCL Server. lnsLead of creaLlng a scrlpL you may as well easlly use Lhe deslgner for creaLlng Lables. Step1: SelecL new 1able .":
Step2: nexL, Lhe Lable deslgner pops up where you can add columns, daLa Lypes, eLc.
ln Lhls deslgner we may also speclfy Column names, uaLa 1ypes, eLc. Step 3: Save Lhe Lable by cllcklng Lhe Save buLLon. 3.3 SCL ConsLralnLs ConsLralnLs are used Lo llmlL Lhe Lype of daLa LhaL can go lnLo a Lable. 17 C8LA1L 1A8LL 1uLorlal: SLrucLured Cuery Language (SCL) ConsLralnLs can be speclfled when a Lable ls creaLed (wlLh Lhe C8LA1L 1A8LL sLaLemenL) or afLer Lhe Lable ls creaLed (wlLh Lhe AL1L8 1A8LL sLaLemenL). Pere are Lhe mosL lmporLanL consLralnLs: 8lMA8? kL? nC1 nuLL unlCuL lC8LlCn kL? CPLCk uLlAuL1 luLn1l1? ln Lhe secLlons below we wlll explaln some of Lhese ln deLall. 3.3.1 8lMA8? kL? 1he 8lMA8? kL? consLralnL unlquely ldenLlfles each record ln a daLabase Lable. rlmary keys musL conLaln unlque values. lL ls normal Lo [usL use runnlng numbers, llke 1, 2, 3, 4, 3, . as values ln rlmary key column. lL ls a good ldea Lo leL Lhe sysLem handle Lhls for you by speclfylng LhaL Lhe rlmary key should be seL Lo |dent|ty(1,1). luLn1l1?(1,1) means Lhe flrsL value wlll be 1 and Lhen lL wlll lncremenL by 1. Lach Lable should have a prlmary key, and each Lable can have only CnL prlmary key. lf we Lake a closer look aL Lhe CuS1CML8 Lable creaLed earller: 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 As you see we use Lhe rlmary key" keyword Lo speclfy LhaL a column should be Lhe rlmary key.
18 C8LA1L 1A8LL 1uLorlal: SLrucLured Cuery Language (SCL) Sett|ng r|mary keys |n the Des|gner 1oo|s: lf you use Lhe ueslgner Lools ln SCL Server you can easlly seL Lhe prlmary key ln a Lable [usL by rlghL-cllck and selecL SeL prlmary key".
1he prlmary key column wlll Lhen have a small key ln fronL Lo lllusLraLe LhaL Lhls column ls a rlmary key. 3.3.2 lC8LlCn kL? A lC8LlCn kL? ln one Lable polnLs Lo a 8lMA8? kL? ln anoLher Lable. Lxample:
We wlll creaLe a C8LA1L 1A8LL scrlpL for Lhese Lables: 19 C8LA1L 1A8LL 1uLorlal: SLrucLured Cuery Language (SCL) SCPCCL: 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 1he lC8LlCn kL? consLralnL ls used Lo prevenL acLlons LhaL would desLroy llnks beLween Lables. 1he lC8LlCn kL? consLralnL also prevenLs LhaL lnvalld daLa from belng lnserLed lnLo Lhe forelgn key column, because lL has Lo be one of Lhe values conLalned ln Lhe Lable lL polnLs Lo. Sett|ng Iore|gn keys |n the Des|gner 1oo|s: lf you wanL Lo use Lhe deslgner, rlghL-cllck on Lhe column LhaL you wanL Lo be Lhe lorelgn key and selecL ke|at|onsh|ps.": 20 C8LA1L 1A8LL 1uLorlal: SLrucLured Cuery Language (SCL)
1he followlng wlndow pops up (lorelgn key 8elaLlonshlps):
Cllck on Lhe Add" buLLon and Lhen cllck on Lhe small ." buLLon. 1hen Lhe followlng wlndow pops up (1ables and Columns): 21 C8LA1L 1A8LL 1uLorlal: SLrucLured Cuery Language (SCL)
Pere you speclfy Lhe prlmary key Column ln Lhe rlmary key Lable and Lhe lorelgn key Column ln Lhe lorelgn key Lable. 3.3.3 nC1 nuLL / 8equlred Columns 1he nC1 nuLL consLralnL enforces a column Lo nC1 accepL nuLL values. 1he nC1 nuLL consLralnL enforces a fleld Lo always conLaln a value. 1hls means LhaL you cannoL lnserL a new record, or updaLe a record wlLhouL addlng a value Lo Lhls fleld. lf we Lake a closer look aL Lhe CuS1CML8 Lable creaLed earller: 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 22 C8LA1L 1A8LL 1uLorlal: SLrucLured Cuery Language (SCL) We see LhaL CusLomernumber", LasLname" and llrsLname" ls seL Lo nC1 nuLL", Lhls means Lhese columns needs Lo conLaln daLa. Whlle AreaCode", Address" and hone" may be lefL empLy, l.e, Lhey don'L need Lo fllled ouL. Note! A prlmary key column cannoL conLaln nuLL values.
Sett|ng NULL]NC1 NULL |n the Des|gner 1oo|s: ln Lhe 1able ueslgner you can easlly seL whlch columns LhaL should allow nuLL or noL:
3.3.4 unlCuL 1he UNIUL consLralnL unlquely ldenLlfles each record ln a daLabase Lable. 1he unlCuL and 8lMA8? kL? consLralnLs boLh provlde a guaranLee for unlqueness for a column or seL of columns. A 8lMA8? kL? consLralnL auLomaLlcally has a unlCuL consLralnL deflned on lL. Note! ?ou can have many unlCuL consLralnLs per Lable, buL only one 8lMA8? kL? consLralnL per Lable. lf we Lake a closer look aL Lhe CuS1CML8 Lable creaLed earller: 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, 23 C8LA1L 1A8LL 1uLorlal: SLrucLured Cuery Language (SCL) Address varchar(50) NULL, Phone varchar(50) NULL, ) GO We see LhaL Lhe CusLomernumber" ls seL Lo unlCuL, meanlng each cusLomer musL have a unlque CusLomer number. Lxample:
Sett|ng UNIUL |n the Des|gner 1oo|s: lf you wanL Lo use Lhe deslgner, rlghL-cllck on Lhe column LhaL you wanL Lo be unlCuL and selecL Indexes]keys.":
1hen cllck Add" and Lhen seL Lhe ls unlque" properLy Lo ?es": 24 C8LA1L 1A8LL 1uLorlal: SLrucLured Cuery Language (SCL)
3.3.3 CPLCk 1he CPLCk consLralnL ls used Lo llmlL Lhe value range LhaL can be placed ln a column. lf you deflne a CPLCk consLralnL on a slngle column lL allows only cerLaln values for Lhls column. lf you deflne a CPLCk consLralnL on a Lable lL can llmlL Lhe values ln cerLaln columns based on values ln oLher columns ln Lhe row. Lxample: 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 ln Lhls case, when we Lry Lo lnserL a CusLomer number less Lhan zero we wlll geL an error message. Sett|ng CnLCk constra|nts |n the Des|gner 1oo|s: lf you wanL Lo use Lhe deslgner, rlghL-cllck on Lhe column where you wanL Lo seL Lhe consLralnLs and selecL Check Constra|nts.": 23 C8LA1L 1A8LL 1uLorlal: SLrucLured Cuery Language (SCL)
1hen cllck Add" and Lhen cllck ." ln order Lo open Lhe Lxpresslon wlndow:
ln Lhe Lxpresslon wlndow you can Lype ln Lhe expresslon you wanL Lo use: 26 C8LA1L 1A8LL 1uLorlal: SLrucLured Cuery Language (SCL)
3.3.6 uLlAuL1 1he uLlAuL1 consLralnL ls used Lo lnserL a defaulL value lnLo a column. 1he defaulL value wlll be added Lo all new records, lf no oLher value ls speclfled. Lxample: 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 Sett|ng DLIAUL1 va|ues |n the Des|gner 1oo|s: SelecL Lhe column and go lnLo Lhe Column roperLles":
27 C8LA1L 1A8LL 1uLorlal: SLrucLured Cuery Language (SCL) 3.3.7 Au1C lnC8LMLn1 or luLn1l1? very ofLen we would llke Lhe value of Lhe prlmary key fleld Lo be creaLed auLomaLlcally every Llme a new record ls lnserLed. Lxample: 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 As shown below, we use Lhe luLn1l1?() for Lhls. luLn1l1?(1,1) means Lhe flrsL value wlll be 1 and Lhen lL wlll lncremenL by 1.
Sett|ng |dent|ty(1,1) |n the Des|gner 1oo|s: We can use Lhe deslgner Lools Lo speclfy LhaL a rlmary key should be an ldenLlLy column LhaL ls auLomaLlcally generaLed by Lhe sysLem when we lnserL daLa ln Lo Lhe Lable. Cllck on Lhe column ln Lhe deslgner and go lnLo Lhe Column roperLles wlndow:
28 C8LA1L 1A8LL 1uLorlal: SLrucLured Cuery Language (SCL) 3.4 AL1L8 1A8LL 1he AL1L8 1A8LL sLaLemenL ls used Lo add, deleLe, or modlfy columns ln an exlsLlng Lable.
1o add a column ln a Lable, use Lhe followlng synLax: ALTER TABLE table_name ADD column_name datatype
1o deleLe a column ln a Lable, use Lhe followlng synLax (noLlce LhaL some daLabase sysLems don'L allow deleLlng a column): ALTER TABLE table_name DROP COLUMN column_name
1o change Lhe daLa Lype of a column ln a Lable, use Lhe followlng synLax: ALTER TABLE table_name ALTER COLUMN column_name datatype
lf we use C8LA1L 1A8LL and Lhe Lable already exlsLs ln Lhe Lable we wlll geL an error message, so lf we comblne C8LA1L 1A8LL and AL1L8 1A8LL we can creaLe robusL daLabase scrlpLs LhaL glves no errors, as Lhe example shown below: 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 29 C8LA1L 1A8LL 1uLorlal: SLrucLured Cuery Language (SCL) Else ALTER TABLE CUSTOMER ADD CustomerNumber int GO
...
30
4 lnSL81 ln1C 1he lnSL81 ln1C sLaLemenL ls used Lo lnserL a new row ln a Lable. lL ls posslble Lo wrlLe Lhe lnSL81 ln1C sLaLemenL ln Lwo forms. 1he flrsL form doesn'L speclfy Lhe column names where Lhe daLa wlll be lnserLed, only Lhelr values: INSERT INTO table_name VALUES (value1, value2, value3,...) Lxample: INSERT INTO CUSTOMER VALUES ('1000', 'Smith', 'John', 12, 'California', '11111111')
1he second form speclfles boLh Lhe column names and Lhe values Lo be lnserLed: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...) 1hls form ls recommended! Lxample: INSERT INTO CUSTOMER (CustomerNumber, LastName, FirstName, AreaCode, Address, Phone) VALUES ('1000', 'Smith', 'John', 12, 'California', '11111111')
Insert Data Cn|y |n Spec|f|ed Co|umns: lL ls also posslble Lo only add daLa ln speclflc columns. Lxample: INSERT INTO CUSTOMER (CustomerNumber, LastName, FirstName) VALUES ('1000', 'Smith', 'John') Note! ?ou need aL leasL Lo lnclude all columns LhaL cannoL be nuLL. We remember Lhe Lable deflnlLlon for Lhe CuS1CML8 Lable: 31 lnSL81 ln1C 1uLorlal: SLrucLured Cuery Language (SCL)
l.e., we need Lo lnclude aL leasL CusLomernumber", LasLname" and llrsLname". CusLomerld" ls seL Lo ldenLlLy(1,1)" and Lherefore values for Lhls column are generaLed by Lhe sysLem. Insert Data |n the Des|gner 1oo|s: When you have creaLed Lhe Lables you can easlly lnserL daLa lnLo Lhem uslng Lhe deslgner Lools. 8lghL-cllck on Lhe speclflc Lable and selecL LdlL 1op 200 8ows":
1hen you can enLer daLa ln a Lable formaL, slmllar Lo, e.g., MS Lxcel:
32
3 uuA1L 1he uuA1L sLaLemenL ls used Lo updaLe exlsLlng records ln a Lable. 1he synLax ls as follows: UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value Note! noLlce Lhe WPL8L clause ln Lhe uuA1L synLax. 1he WPL8L clause speclfles whlch record or records LhaL should be updaLed. lf you omlL Lhe WPL8L clause, all records wlll be updaLed! Lxample: update CUSTOMER set AreaCode=46 where CustomerId=2 8efore updaLe:
AfLer updaLe:
lf you don'L lnclude Lhe WPL8L clause Lhe resulL becomes:
- So make sure Lo lnclude Lhe WPL8L clause when uslng Lhe uuA1L command!
33 uuA1L 1uLorlal: SLrucLured Cuery Language (SCL) Update Data |n the Des|gner 1oo|s: 1he same way you lnserL daLa you can also updaLe Lhe daLa. 8lghL-cllck on Lhe speclflc Lable and selecL LdlL 1op 200 8ows":
1hen you can change your daLa:
34
6 uLLL1L 1he uLLL1L sLaLemenL ls used Lo deleLe rows ln a Lable. SynLax: DELETE FROM table_name WHERE some_column=some_value Note! noLlce Lhe WPL8L clause ln Lhe uLLL1L synLax. 1he WPL8L clause speclfles whlch record or records LhaL should be deleLed. lf you omlL Lhe WPL8L clause, all records wlll be deleLed! Lxample: delete from CUSTOMER where CustomerId=2 8efore deleLe:
AfLer deleLe:
De|ete A|| kows: lL ls posslble Lo deleLe all rows ln a Lable wlLhouL deleLlng Lhe Lable. 1hls means LhaL Lhe Lable sLrucLure, aLLrlbuLes, and lndexes wlll be lnLacL: DELETE FROM table_name Note! Make sure Lo do Lhls only when you really mean lL! ?ou cannoL unuC Lhls sLaLemenL! De|ete Data |n the Des|gner 1oo|s: ?ou deleLe daLa ln Lhe deslgner by rlghL-cllck on Lhe row and selecL ueleLe": 33 uLLL1L 1uLorlal: SLrucLured Cuery Language (SCL)
36
7 SLLLC1 1he SLLLC1 sLaLemenL ls probably Lhe mosL used SCL command. 1he SLLLC1 sLaLemenL ls used for reLrlevlng rows from Lhe daLabase and enables Lhe selecLlon of one or many rows or columns from one or many Lables ln Lhe daLabase. We wlll use Lhe CuS1CML8 Lable as an example. 1he CuS1CML8 Lable has Lhe followlng columns:
1he CuS1CML8 Lable conLalns Lhe followlng daLa:
Lxample: select * from CUSTOMER
1hls slmple example geLs all Lhe daLa ln Lhe Lable CuS1CML8. 1he symbol *" ls used when you wanL Lo geL all Lhe columns ln Lhe Lable.
37 SLLLC1 1uLorlal: SLrucLured Cuery Language (SCL) lf you only wanL a few columns, you may speclfy Lhe names of Lhe columns you wanL Lo reLrleve, example: select CustomerId, LastName, FirstName from CUSTOMER
So ln Lhe slmplesL form we can use Lhe SLLLC1 sLaLemenL as follows: select <column_names> from <table_names> lf we wanL all columns, we use Lhe symbol *" Note! SCL ls noL case senslLlve. SLLLC1 ls Lhe same as selecL. 1he full synLax of Lhe SLLLC1 sLaLemenL ls complex, buL Lhe maln clauses can be summarlzed 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 ] ] lL seems complex, buL we wlll Lake Lhe dlfferenL parLs sLep by sLep ln Lhe nexL secLlons. Se|ect Data |n the Des|gner 1oo|s: 8lghL-cllck on a Lable and selecL SelecL 1op 1000 8ows":
A SelecL query ls auLomaLlcally creaLed for you whlch you can edlL lf you wanL Lo. 7.1 1he C8uL8 8? keyword lf you wanL Lhe daLa Lo appear ln a speclflc order you need Lo use Lhe order by" keyword. Lxample: select * from CUSTOMER order by LastName
?ou may also sorL by several columns, e.g. llke Lhls: select * from CUSTOMER order by Address, LastName
lf you use Lhe order by" keyword, Lhe defaulL order ls ascendlng (asc"). lf you wanL Lhe order Lo be opposlLe, l.e., descendlng, Lhen you need Lo use Lhe desc" keyword. 39 SLLLC1 1uLorlal: SLrucLured Cuery Language (SCL) select * from CUSTOMER order by LastName desc
7.2 SLLLC1 ulS1lnC1 ln a Lable, some of Lhe columns may conLaln dupllcaLe values. 1hls ls noL a problem, however, someLlmes you wlll wanL Lo llsL only Lhe dlfferenL (dlsLlncL) values ln a Lable. 1he ulS1lnC1 keyword can be used Lo reLurn only dlsLlncL (dlfferenL) values. 1he synLax ls as follows: select distinct <column_names> from <table_names>
Lxample: select distinct FirstName from CUSTOMER
7.3 1he WPL8L Clause 1he WPL8L clause ls used Lo exLracL only Lhose records LhaL fulflll a speclfled crlLerlon. 1he synLax ls as follows: select <column_names> from <table_name> where <column_name> operator value
Lxample: select * from CUSTOMER where CustomerNumber='1001'
40 SLLLC1 1uLorlal: SLrucLured Cuery Language (SCL) Note! SCL uses slngle quoLes around LexL values, as shown ln Lhe example above. 7.3.1 CperaLors WlLh Lhe WPL8L clause, Lhe followlng operaLors can be used: Cperator Descr|pt|on = Lqual <> noL equal > CreaLer Lhan < Less Lhan >= CreaLer Lhan or equal <= Less Lhan or equal 8L1WLLN 8eLween an lncluslve range LIkL Search for a paLLern IN lf you know Lhe exacL value you wanL Lo reLurn for aL leasL one of Lhe columns Lxamples: select * from CUSTOMER where AreaCode>30
7.3.2 LlkL CperaLor 1he LlkL operaLor ls used Lo search for a speclfled paLLern ln a column. SynLax: SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern Lxample: select * from CUSTOMER where LastName like 'J%'
Note! 1he "" slgn can be used Lo deflne wlldcards (mlsslng leLLers ln Lhe paLLern) boLh before and afLer Lhe paLLern. 41 SLLLC1 1uLorlal: SLrucLured Cuery Language (SCL)
select * from CUSTOMER where LastName like '%a%'
?ou may also comblne wlLh Lhe nC1 keyword, example: select * from CUSTOMER where LastName not like '%a%'
7.3.3 ln CperaLor 1he ln operaLor allows you Lo speclfy mulLlple values ln a WPL8L clause. SynLax: SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,...) 7.3.4 8L1WLLn CperaLor 1he 8L1WLLn operaLor selecLs a range of daLa beLween Lwo values. 1he values can be numbers, LexL, or daLes. SynLax: SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2 7.4 Wlldcards SCL wlldcards can subsLlLuLe for one or more characLers when searchlng for daLa ln a daLabase. Note! SCL wlldcards musL be used wlLh Lhe SCL LlkL operaLor. WlLh SCL, Lhe followlng wlldcards can be used: 42 SLLLC1 1uLorlal: SLrucLured Cuery Language (SCL) W||dcard Descr|pt|on A subsLlLuLe for zero or more characLers _ A subsLlLuLe for exacLly one characLer [char||st] Any slngle characLer ln charllsL [^char||st] or [!char||st] Any slngle characLer noL ln charllsL Lxamples: SELECT * FROM CUSTOMER WHERE LastName LIKE 'J_cks_n'
SELECT * FROM CUSTOMER WHERE CustomerNumber LIKE '[10]%'
7.3 Anu & C8 CperaLors 1he Anu operaLor dlsplays a record lf boLh Lhe flrsL condlLlon and Lhe second condlLlon ls Lrue. 1he C8 operaLor dlsplays a record lf elLher Lhe flrsL condlLlon or Lhe second condlLlon ls Lrue. Lxamples: select * from CUSTOMER where LastName='Smith' and FirstName='John'
select * from CUSTOMER where LastName='Smith' or FirstName='John'
Comb|n|ng AND & Ck: 43 SLLLC1 1uLorlal: SLrucLured Cuery Language (SCL) ?ou can also comblne Anu and C8 (use parenLhesls Lo form complex expresslons). Lxample: select * from CUSTOMER where LastName='Smith' and (FirstName='John' or FirstName='Smith')
7.6 SLLLC1 1C Clause 1he 1C clause ls used Lo speclfy Lhe number of records Lo reLurn. 1he 1C clause can be very useful on large Lables wlLh Lhousands of records. 8eLurnlng a large number of records can lmpacL on performance. SynLax: SELECT TOP number|percent column_name(s) FROM table_name
Lxamples: select TOP 1 * from CUSTOMER
?ou can also speclfy ln percenL: select TOP 60 percent * from CUSTOMER
1hls ls very useful for large Lables wlLh Lhousands of records 7.7 Allas 44 SLLLC1 1uLorlal: SLrucLured Cuery Language (SCL) ?ou can glve a Lable or a column anoLher name by uslng an allas. 1hls can be a good Lhlng Lo do lf you have very long or complex Lable names or column names. An allas name could be anyLhlng, buL usually lL ls shorL. SL A||as Syntax for 1ab|es: SELECT column_name(s) FROM table_name AS alias_name SL A||as Syntax for Co|umns: SELECT column_name AS alias_name FROM table_name 7.8 !olns SCL [olns are used Lo query daLa from Lwo or more Lables, based on a relaLlonshlp beLween cerLaln columns ln Lhese Lables.
43 SLLLC1 1uLorlal: SLrucLured Cuery Language (SCL) 7.8.1 ulfferenL SCL !Clns 8efore we conLlnue wlLh examples, we wlll llsL Lhe Lypes of !Cln you can use, and Lhe dlfferences beLween Lhem. !Cln: 8eLurn rows when Lhere ls aL leasL one maLch ln boLh Lables LLl1 !Cln: 8eLurn all rows from Lhe lefL Lable, even lf Lhere are no maLches ln Lhe rlghL Lable 8lCP1 !Cln: 8eLurn all rows from Lhe rlghL Lable, even lf Lhere are no maLches ln Lhe lefL Lable luLL !Cln: 8eLurn rows when Lhere ls a maLch ln one of Lhe Lables
Lxample: Clven 2 Lables: SCPCCL CLASS 1he dlagram ls shown below:
We wanL Lo geL Lhe followlng lnformaLlon uslng a query: Schoolname Classname . . . . ln order Lo geL lnformaLlon from more Lhan one Lable we need Lo use Lhe !Cln. 1he !Cln ls used Lo [oln Lhe prlmary key ln one Lable wlLh Lhe forelgn key ln anoLher Lable. 46 SLLLC1 1uLorlal: SLrucLured Cuery Language (SCL) select SCHOOL.SchoolName, CLASS.ClassName from SCHOOL INNER JOIN CLASS ON SCHOOL.SchoolId = CLASS.SchoolId
47
8 SCL ScrlpLs A SCL scrlpL ls a collecLlon of SCL sLaLemenLs LhaL you can execuLe ln one operaLlon. ?ou can use any klnd of SCL commands, such as lnserL, selecL, deleLe, updaLe, eLc. ln addlLlon you can deflne and use varlables, and you may also use program flow llke lf-Llse, eLc. ?ou may also add commenLs Lo make Lhe scrlpL easler Lo read and undersLand. 8.1 uslng CommenLs uslng commenLs ln you SCL scrlpL ls lmporLanL Lo make Lhe scrlpL easler Lo read and undersLand. ln SCL we can use 2 dlfferenL klnds of commenLs: Slngle-llne commenL MulLlple-llne commenL 8.1.1 Slngle-llne commenL We can commenL one llne aL Lhe Llme uslng --" before Lhe LexL you wanL Lo commenL ouL. SynLax: -- text_of_comment 8.1.2 MulLlple-llne commenL We can commenL several llne uslng ]*" ln Lhe sLarL of Lhe commenL and *]" ln Lhe end of Lhe commenL. SynLax: /* text_of_comment text_of_comment */ 48 SCL ScrlpLs 1uLorlal: SLrucLured Cuery Language (SCL) 8.2 varlables 1he ablllLy Lo uslng varlables ln SCL ls a powerful feaLure. ?ou need Lo use Lhe keyword DLCLAkL when you wanL Lo deflne Lhe varlables. Local varlables musL have Lhe Lhe symbol [" as a preflx. ?ou also need Lo speclfy a daLa Lype for your varlable (lnL, varchar(x), eLc.). SynLax for declarlng varlables: declare @local_variable data_type
lf you have more Lhan one varlable you wanL Lo declare: declare @myvariable1 data_type, @myvariable2 data_type,
When you wanL Lo asslgn values Lo Lhe varlable, you musL use elLher a SL1 or a SLLLC1 sLaLemenL. Lxample: declare @myvariable int
set @myvariable=4
lf you wanL Lo see Lhe value for a varlable, you can e.g., use Lhe kIN1 command llke Lhls: declare @myvariable int
set @myvariable=4
print @myvariable 1he followlng wlll be shown ln SCL Server:
Asslgnlng varlables wlLh a value from a SLLLC1 sLaLemenL ls very useful. 49 SCL ScrlpLs 1uLorlal: SLrucLured Cuery Language (SCL) We use Lhe CuS1CML8 Lable as an example:
?ou can asslgn a value Lo Lhe varlable from a selecL sLaLemenL llke Lhls: declare @mylastname varchar(50)
select @mylastname=LastName from CUSTOMER where CustomerId=2 print @mylastname
?ou can also use a varlable ln Lhe WPL8L clause LlkL, e.g., Lhls: declare @find varchar(30) set @find = 'J%' select * from CUSTOMER where LastName LIKE @find
8.3 8ullL-ln Clobal varlables SCL have loLs of bullL-ln varlables LhaL are very useful Lo use ln querles and scrlpLs. 8.3.1 [[luLn1l1? AfLer an lnSL81, SLLLC1 ln1C, or bulk copy sLaLemenL ls compleLed, [[luLn1l1? conLalns Lhe lasL ldenLlLy value LhaL ls generaLed by Lhe sLaLemenL. lf Lhe sLaLemenL dld noL affecL any Lables wlLh ldenLlLy columns, [[luLn1l1? reLurns nuLL. lf mulLlple rows are lnserLed, generaLlng mulLlple ldenLlLy values, [[luLn1l1? reLurns Lhe lasL ldenLlLy value generaLed. Lxamp|e: Clven Lo Lables, SCPCCL and CCu8SL: 30 SCL ScrlpLs 1uLorlal: SLrucLured Cuery Language (SCL) SCPCCL Lable: CCu8SL Lable:
We wanL Lo lnserL a new School lnLo Lhe SCPCCL Lable and we wanL Lo lnserL 2 new Courses ln Lhe CCu8SL Lable LhaL belong Lo Lhe School we lnserL. 1o flnd Lhe Schoolld" we can use Lhe [[luLn1l1? varlable: 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, 'MIT-101') insert into COURSE(SchoolId,CourseName) values (@SchoolId, 'MIT-201') 1he resulL becomes: SCPCCL Lable: CCu8SL Lable:
8.4 llow ConLrol As wlLh oLher programmlng languages you can use dlfferenL klnd of flow conLrol, such as ll-LLSL, WPlLL, eLc, whlch ls very useful. 8.4.1 ll - LLSL 1he ll-LLSL ls very useful. 8elow we see an example: declare @customerNumber int
select @customerNumber=CustomerNumber from CUSTOMER where CustomerId=2 31 SCL ScrlpLs 1uLorlal: SLrucLured Cuery Language (SCL)
if @customerNumber > 1000 print 'The Customer Number is larger than 1000' else print 'The Customer Number is not larger than 1000'
8LGIN.LND: lf more Lhan one llne of code ls Lo be execuLed wlLhln an ll senLence you need Lo use 8LGIN.LND. Lxample: 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 WPlLL We can also use WPlLL, whlch ls known from oLher programmlng languages. Lxamp|e: We are uslng Lhe CuS1CML8 Lable:
and Lhe followlng query: while (select AreaCode from CUSTOMER where CustomerId=1) < 20 begin update CUSTOMER set AreaCode = AreaCode + 1 end
select * from CUSTOMER 32 SCL ScrlpLs 1uLorlal: SLrucLured Cuery Language (SCL)
As you can see Lhe code lnslde Lhe WPlLL loop ls execuLed as long as AreaCode" for CusLomerld=1 ls less Lhan 20. lor each lLeraLlon ls Lhe AreaCode" for LhaL cusLomer lncremenLed wlLh 1. 8.4.3 CASL 1he CASL sLaLemenL evaluaLes a llsL of condlLlons and reLurns one of mulLlple posslble resulL expresslons. Lxample: We have a C8AuL" Lable LhaL conLalns Lhe grades for each sLudenL ln dlfferenL courses: select GradeId, StudentId, CourseId, Grade from GRADE
ln Lhe C8AuL" Lable ls Lhe grades sLored as numbers, buL slnce Lhe sLudenLs geL grades wlLh Lhe leLLers A..l (A=3, 8=4, C=3, u=2, L=1, l=0), we wanL Lo converL Lhe values ln Lhe Lable lnLo leLLers uslng a CASL sLaLemenL: select GradeId, StudentId, CourseId, case Grade when 5 then 'A' when 4 then 'B' when 3 then 'C' when 2 then 'D' when 1 then 'E' when 0 then 'F' else '-' end as Grade from GRADE 33 SCL ScrlpLs 1uLorlal: SLrucLured Cuery Language (SCL)
8.4.4 Cu8SC8 ln advances scrlpLs, Cu8SC8s may be very useful. A Cu8SC8 works llke an advanced WPlLL loop whlch we use Lo lLeraLe Lhrough Lhe records ln one or more Lables. Cu8SC8S are used malnly ln sLored procedures, Lrlggers, and SCL scrlpLs. Lxamp|e: We use Lhe CuS1CML8 Lable as an example:
We wlll creaLe a Cu8SC8 LhaL lLeraLe Lhrough all Lhe records ln Lhe CuS1CML8 Lable and check lf Lhe hone number conslsLs of 8 dlglLs, lf noL Lhe scrlpL wlll replace Lhe lnvalld hone number wlLh Lhe LexL hone number ls noL valld". Pere ls Lhe SCL ScrlpL uslng a Cu8SC8: 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 update CUSTOMER set Phone='Phone number is not valid' where CustomerId=@CustomerId 34 SCL ScrlpLs 1uLorlal: SLrucLured Cuery Language (SCL)
FETCH NEXT FROM db_cursor INTO @CustomerId END
CLOSE db_cursor DEALLOCATE db_cursor
1he CuS1CML8 Lable becomes:
CreaLlng and uslng a Cu8SC8 lncludes Lhese sLeps: ueclare SCL varlables Lo conLaln Lhe daLa reLurned by Lhe cursor. ueclare one varlable for each resulL seL column. AssoclaLe a SCL cursor wlLh a SLLLC1 sLaLemenL uslng Lhe uLCLA8L Cu8SC8 sLaLemenL. 1he uLCLA8L Cu8SC8 sLaLemenL also deflnes Lhe characLerlsLlcs of Lhe cursor, such as Lhe cursor name and wheLher Lhe cursor ls read-only or forward-only. use Lhe CLn sLaLemenL Lo execuLe Lhe SLLLC1 sLaLemenL and populaLe Lhe cursor. use Lhe lL1CP ln1C sLaLemenL Lo feLch lndlvldual rows and have Lhe daLa for each column moved lnLo a speclfled varlable. CLher SCL sLaLemenLs can Lhen reference Lhose varlables Lo access Lhe feLched daLa values. When you are flnlshed wlLh Lhe cursor, use Lhe CLCSL sLaLemenL. Closlng a cursor frees some resources, such as Lhe cursor's resulL seL and lLs locks on Lhe currenL row. 1he uLALLCCA1L sLaLemenL compleLely frees all resources allocaLed Lo Lhe cursor, lncludlng Lhe cursor name.
33
9 vlews vlews are vlrLual Lable for easler access Lo daLa sLored ln mulLlple Lables.
SynLax for creaLlng a vlew: CREATE VIEW <ViewName> AS
... buL lL mlghL be easler Lo do lL ln Lhe graphlcal vlew deslgner LhaL are bullL lnLo SCL ManagemenL SLudlo. SynLax for uslng a vlew: select * from <MyView> where As shown above, we use a vlLW [usL llke we use an ordlnary Lable. 36 vlews 1uLorlal: SLrucLured Cuery Language (SCL) Lxamp|e: We use Lhe SCPCCL and CLASS Lables as an example for our vlew. We wanL Lo creaLe a vlew LhaL llsLs all Lhe exlsLlng schools and Lhe belonglng classes.
We creaLe Lhe vlLW uslng Lhe C8LA1L vlLW command: CREATE VIEW SchoolView AS
SELECT SCHOOL.SchoolName, CLASS.ClassName FROM SCHOOL INNER JOIN CLASS ON SCHOOL.SchoolId = CLASS.SchoolId Note! ln order Lo geL lnformaLlon from more Lhan one Lable, we need Lo llnk Lhe Lables LogeLher uslng a !Cln. 9.1 uslng Lhe Craphlcal ueslgner We creaLe Lhe same vlew uslng Lhe graphlcal deslgner ln SCL Server ManagemenL SLudlo: 37 vlews 1uLorlal: SLrucLured Cuery Language (SCL)
Step 1: 8lghL-cllck on Lhe vlew node and selecL new vlew.":
39 vlews 1uLorlal: SLrucLured Cuery Language (SCL) SLep 3: use Lhe vlLW ln a query: select * from SchoolView
60
10 SLored rocedures A SLored rocedure ls a precomplled collecLlon of SCL sLaLemenLs. ln a sLored procedure you can use lf senLence, declare varlables, eLc.
SynLax for creaLlng a SLored rocedure: CREATE PROCEDURE <ProcedureName> @<Parameter1> <datatype>
declare @myVariable <datatype> Create your Code here Note! ?ou need Lo use Lhe symbol [" before varlable names. SynLax for uslng a SLored rocedure: EXECUTE <ProcedureName()> Lxamp|e: 61 SLored rocedures 1uLorlal: SLrucLured Cuery Language (SCL) We use Lhe SCPCCL and CLASS Lables as an example for our SLored rocedure. We wanL Lo creaLe a SLored rocedure LhaL llsLs all Lhe exlsLlng schools and Lhe belonglng classes.
We creaLe Lhe SLored rocedure as follows: CREATE PROCEDURE GetAllSchoolClasses AS
select SCHOOL.SchoolName, CLASS.ClassName from SCHOOL inner join CLASS on SCHOOL.SchoolId = CLASS.SchoolId order by SchoolName, ClassName
When we have creaLed Lhe SLored rocedure we can run (or execuLe) Lhe SLored procedure uslng Lhe execuLe command llke Lhls: execute GetAllSchoolClasses
We can also creaLe a SLore rocedure wlLh lnpuL parameLers. Lxamp|e: 62 SLored rocedures 1uLorlal: SLrucLured Cuery Language (SCL) We use Lhe same Lables ln Lhls example (SCPCCL and CLASS) buL now we wanL Lo llsL all classes for a speclflc school. 1he SLored rocedure becomes: 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 We run (or execuLe) Lhe SLored rocedure: execute GetSpecificSchoolClasses 'TUC'
or: execute GetSpecificSchoolClasses 'NTNU'
When we Lry Lo creaLe a SLored rocedure LhaL already exlsLs we geL Lhe followlng error message: There is already an object named 'GetSpecificSchoolClasses' in the database. 1hen we flrsL need Lo deleLe (or u8C) Lhe old SLored rocedure before we can recreaLe lL agaln. We can do Lhls manually ln Lhe ManagemenL SLudlo ln SCL llke Lhls: 63 SLored rocedures 1uLorlal: SLrucLured Cuery Language (SCL)
A beLLer soluLlon ls Lo add code for Lhls ln our scrlpL, llke Lhls: 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 So we use C8LA1L 8CCLuu8L Lo creaLe a SLored rocedure and we use u8C 8CCLuu8L Lo deleLe a SLored rocedure. 10.1 nCCCun1 Cn/nCCCun1 Cll ln advanced SLored rocedures and ScrlpL, performance ls very lmporLanL. uslng SL1 nCCCun1 Cn and SL1 nCCCun1 Cll makes Lhe SLored rocedure run fasLer. SL1 nCCCun1 Cn sLops Lhe message LhaL shows Lhe counL of Lhe number of rows affecLed by a 1ransacL-SCL sLaLemenL or sLored procedure from belng reLurned as parL of Lhe resulL seL. 64 SLored rocedures 1uLorlal: SLrucLured Cuery Language (SCL) SL1 nCCCun1 Cn prevenLs Lhe sendlng of uCnL_ln_8CC messages Lo Lhe cllenL for each sLaLemenL ln a sLored procedure. lor sLored procedures LhaL conLaln several sLaLemenLs LhaL do noL reLurn much acLual daLa, or for procedures LhaL conLaln 1ransacL-SCL loops, seLLlng SL1 nCCCun1 Lo Cn can provlde a slgnlflcanL performance boosL, because neLwork Lrafflc ls greaLly reduced. Lxamp|e: IF EXISTS (SELECT name FROM sysobjects WHERE name = 'sp_LIMS_IMPORT_REAGENT' AND type = 'P') DROP PROCEDURE sp_LIMS_IMPORT_REAGENT GO
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 1hls SLored rocedure updaLes a Lable ln Lhe daLabase and ln Lhls case you don'L normally need feedback, sp seLLlng SL1 nCCCun1 Cn aL Lhe Lop ln Lhe sLored procedure ls a good ldea. lL ls also good pracLlce Lo SL1 nCCCun1 Cll aL Lhe boLLom of Lhe sLored procedure.
63
11 luncLlons WlLh SCL and SCL Server you can use loLs of bullL-ln funcLlons or you may creaLe your own funcLlons. Pere we wlll learn Lo use some of Lhe mosL used bullL-ln funcLlons and ln addlLlon we wlll creaLe our own funcLlon. 11.1 8ullL-ln luncLlons SCL has many bullL-ln funcLlons for performlng calculaLlons on daLa. We have 2 caLegorles of funcLlons, namely aggregate funcLlons and sca|ar funcLlons. AggregaLe funcLlons reLurn a slngle value, calculaLed from values ln a column, whlle scalar funcLlons reLurn a slngle value, based on Lhe lnpuL value. Aggregate funcLlons - examples: AVG() - 8eLurns Lhe average value S1DLV() - 8eLurns Lhe sLandard devlaLlon value CCUN1() - 8eLurns Lhe number of rows MAk() - 8eLurns Lhe largesL value MIN() - 8eLurns Lhe smallesL value SUM() - 8eLurns Lhe sum eLc. Sca|ar funcLlons - examples: ULk() - ConverLs a fleld Lo upper case LCWLk() - ConverLs a fleld Lo lower case LLN() - 8eLurns Lhe lengLh of a LexL fleld kCUND() - 8ounds a numerlc fleld Lo Lhe number of declmals speclfled GL1DA1L() - 8eLurns Lhe currenL sysLem daLe and Llme eLc. 11.1.1 SLrlng luncLlons Pere are some useful funcLlons used Lo manlpulaLe wlLh sLrlngs ln SCL Server: 66 luncLlons 1uLorlal: SLrucLured Cuery Language (SCL) CPA8 CPA8lnuLx 8LLACL Su8S18lnC LLn 8LvL8SL LLl1 8lCP1 LCWL8 uL8 L18lM 818lM 8ead more abouL Lhese funcLlons ln Lhe SCL Server Pelp. 11.1.2 uaLe and 1lme luncLlons Pere are some useful uaLe and 1lme funcLlons ln SCL Server: uA1LA81 CL1uA1L uA1LAuu uA1Lulll uA? MCn1P ?LA8 lSuA1L 8ead more abouL Lhese funcLlons ln Lhe SCL Server Pelp. 11.1.3 MaLhemaLlcs and SLaLlsLlcs luncLlons Pere are some useful funcLlons for maLhemaLlcs and sLaLlsLlcs ln SCL Server: CCun1 Mln, MAx CCS, Sln, 1An SC81 S1uLv MLAn AvC 67 luncLlons 1uLorlal: SLrucLured Cuery Language (SCL) 8ead more abouL Lhese funcLlons ln Lhe SCL Server Pelp. 11.1.4 AvC() 1he AvC() funcLlon reLurns Lhe average value of a numerlc column. SynLax: SELECT AVG(column_name) FROM table_name Lxample: Clven a C8AuL Lable:
We wanL Lo flnd Lhe average grade for a speclflc sLudenL: select AVG(Grade) as AvgGrade from GRADE where StudentId=1
11.1.3 CCun1() 1he CCun1() funcLlon reLurns Lhe number of rows LhaL maLches a speclfled crlLerla.
1he CCun1(column_name) funcLlon reLurns Lhe number of values (nuLL values wlll noL be counLed) of Lhe speclfled column: SELECT COUNT(column_name) FROM table_name
1he CCun1(*) funcLlon reLurns Lhe number of records ln a Lable: SELECT COUNT(*) FROM table_name
68 luncLlons 1uLorlal: SLrucLured Cuery Language (SCL) We use Lhe CuS1CML8 Lable as an example:
select COUNT(*) as NumbersofCustomers from CUSTOMER
11.1.6 1he C8Cu 8? SLaLemenL AggregaLe funcLlons ofLen need an added C8Cu 8? sLaLemenL. 1he C8Cu 8? sLaLemenL ls used ln con[uncLlon wlLh Lhe aggregaLe funcLlons Lo group Lhe resulL-seL by one or more columns. SynLax SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name Lxample: We use Lhe CuS1CML8 Lable as an example:
lf we Lry Lhe followlng: select FirstName, MAX(AreaCode) from CUSTOMER We geL Lhe followlng error message: Column 'CUSTOMER.FirstName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. 1he soluLlon ls Lo use Lhe C8Cu 8?: select FirstName, MAX(AreaCode) from CUSTOMER group by FirstName 69 luncLlons 1uLorlal: SLrucLured Cuery Language (SCL)
11.1.7 1he PAvlnC Clause 1he PAvlnC clause was added Lo SCL because Lhe WPL8L keyword could noL be used wlLh aggregaLe funcLlons. SynLax: 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
We use Lhe C8AuL Lable as an example: select * from GRADE
llrsL we use Lhe C8Cu 8? sLaLemenL: select CourseId, AVG(Grade) from GRADE group by CourseId
Whlle Lhe followlng query: select CourseId, AVG(Grade) from GRADE group by CourseId having AVG(Grade)>3
70 luncLlons 1uLorlal: SLrucLured Cuery Language (SCL) 11.2 user-deflned luncLlons ln SCL we may also creaLe our own funcLlons, so-called user-deflned funcLlons. A user-deflned funcLlon ls a rouLlne LhaL accepLs parameLers, performs an acLlon, such as a complex calculaLlon, and reLurns Lhe resulL of LhaL acLlon as a value. 1he reLurn value can elLher be a scalar (slngle) value or a Lable. use Lhls sLaLemenL Lo creaLe a reusable rouLlne LhaL can be used ln oLher querles.
ln SCL daLabases, a user-deflned funcLlon provldes a mechanlsm for exLendlng Lhe funcLlonallLy of Lhe daLabase server by addlng a funcLlon LhaL can be evaluaLed ln SCL sLaLemenLs. 1he SCL sLandard dlsLlngulshes beLween scalar and Lable funcLlons. A scalar funcLlon reLurns only a slngle value (or nuLL), whereas a Lable funcLlon reLurns a (relaLlonal) Lable comprlslng zero or more rows, each row wlLh one or more columns. SLored rocedures vs. luncLlons: Cnly funcLlons can reLurn a value (uslng Lhe 8L1u8n keyword). SLored procedures can use 8L1u8n keyword buL wlLhouL any value belng passed[1] luncLlons could be used ln SLLLC1 sLaLemenLs, provlded Lhey don'L do any daLa manlpulaLlon and also should noL have any Cu1 or ln Cu1 parameLers. luncLlons musL reLurn a value, buL for sLored procedures Lhls ls noL compulsory. A funcLlon can have only ln parameLers, whlle sLored procedures may have Cu1 or ln Cu1 parameLers. A funcLlon ls a subprogram wrlLLen Lo perform cerLaln compuLaLlons and reLurn a slngle value. A sLored procedure ls a subprogram wrlLLen Lo perform a seL of acLlons, and can reLurn mulLlple values uslng Lhe Cu1 parameLer or reLurn no value aL all.
user-deflned funcLlons ln SCL are declared uslng Lhe CkLA1L IUNC1ICN sLaLemenL. When we have creaLed Lhe funcLlon, we can use Lhe funcLlon Lhe same way we use bullL-ln funcLlons.
71
12 1rlggers A daLabase Lrlgger ls code LhaL ls auLomaLlcally execuLed ln response Lo cerLaln evenLs on a parLlcular Lable ln a daLabase.
SynLax for creaLlng a 1rlgger: CREATE TRIGGER <TriggerName> on <TableName> FOR INSERT, UPDATE, DELETE AS Create your Code here GO 1he 1rlgger wlll auLomaLlcally be execuLed when daLa ls lnserLed, updaLed or deleLed ln Lhe Lable as speclfled ln Lhe 1rlgger header. INSLk1LD and DLLL1LD: lnslde Lrlggers we can use Lwo speclal Lables: Lhe uLLL1Lu Lable and Lhe lnSL81Lu Lables. SCL Server auLomaLlcally creaLes and manages Lhese Lables. ?ou can use Lhese Lemporary, 72 1rlggers 1uLorlal: SLrucLured Cuery Language (SCL) memory-resldenL Lables Lo LesL Lhe effecLs of cerLaln daLa modlflcaLlons. ?ou cannoL modlfy Lhe daLa ln Lhese Lables. 1he uLLL1Lu Lable sLores coples of Lhe affecLed rows durlng uLLL1L and uuA1L sLaLemenLs. uurlng Lhe execuLlon of a uLLL1L or uuA1L sLaLemenL, rows are deleLed from Lhe Lrlgger Lable and Lransferred Lo Lhe uLLL1Lu Lable. 1he lnSL81Lu Lable sLores coples of Lhe affecLed rows durlng lnSL81 and uuA1L sLaLemenLs. uurlng an lnserL or updaLe LransacLlon, new rows are added Lo boLh Lhe lnSL81Lu Lable and Lhe Lrlgger Lable. 1he rows ln Lhe lnSL81Lu Lable are coples of Lhe new rows ln Lhe Lrlgger Lable. Lxamp|e: We wlll use Lhe CuS1CML8 Lable as an example:
We wlll creaLe a 18lCCL8 LhaL wlll check lf Lhe hone number ls valld when we lnserL or updaLe daLa ln Lhe CuS1CML8 Lable. 1he valldaLlon check wlll be very slmple, l.e., we wlll check lf Lhe hone number ls less Lhan 8 dlglLs (whlch ls normal lengLh ln norway). lf Lhe hone number ls less Lhan 8 dlglLs, Lhe followlng message hone number ls noL valld" be wrlLLen ln place of Lhe wrong number ln Lhe hone column. 1he 18lCCL8 becomes someLhlng llke Lhls: 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
As you can see, Lhe 18lCCL8 works as expecLed. We Lry Lo updaLe Lhe hone number Lo a valld number: update CUSTOMER set Phone = '44444444' where CustomerNumber = '1003' 1he resulLs become:
74
13 CommunlcaLe from oLher AppllcaLlons A uaLabase ls a sLrucLured way Lo sLore loLs of lnformaLlon. 1he lnformaLlon ls sLored ln dlfferenL Lables. LveryLhlng" Loday ls sLored ln daLabases. Lxamples: 8ank/AccounL sysLems lnformaLlon ln Web pages such as lacebook, Wlklpedla, ?ou1ube . loLs of oLher examples 1hls means we need Lo be able Lo communlcaLe wlLh Lhe daLabase from oLher appllcaLlons and programmlng languages ln order Lo lnserL, updaLe or reLrleve daLa from Lhe daLabase. 13.1 Cu8C Cu8C (Cpen uaLabase ConnecLlvlLy) ls a sLandardlzed lnLerface (Al) for accesslng Lhe daLabase from a cllenL. ?ou can use Lhls sLandard Lo communlcaLe wlLh daLabases from dlfferenL vendors, such as Cracle, SCL Server, eLc. 1he deslgners of Cu8C almed Lo make lL lndependenL of programmlng languages, daLabase sysLems, and operaLlng sysLems. We wlll use Lhe Cu8C uaLa Source AdmlnlsLraLor:
73 CommunlcaLe from oLher AppllcaLlons 1uLorlal: SLrucLured Cuery Language (SCL)
13.2 MlcrosofL Lxcel MlcrosofL Lxcel has Lhe ablllLy Lo reLrleve daLa from dlfferenL daLa sources, lncludlng dlfferenL daLabase sysLems. lL ls very slmple Lo reLrleve daLa from SCL Server lnLo Lxcel slnce Lxcel and SCL Server has Lhe same vendor (MlcrosofL).
76 CommunlcaLe from oLher AppllcaLlons 1uLorlal: SLrucLured Cuery Language (SCL)
77
14 8eferences MlcrosofL offlclal SCL Server Web slLe - http:]]www.m|crosoft.com]sq|server SCL Server 8ooks Cnllne - http:]]msdn.m|crosoft.com]en-us]||brary]ms166020.aspx SCL Server Pelp w3shools.com - http:]]www.w3schoo|s.com]sq| Wlklpedla - MlcrosofL SCL Server - http:]]en.w|k|ped|a.org]w|k|]M|crosoft_SL_Server Wlklpedla - SCL - http:]]en.w|k|ped|a.org]w|k|]SL Wlklpedla - 1ransacL SCL - http:]]en.w|k|ped|a.org]w|k|]1-SL
nans-etter na|vorsen, M.Sc. 1e|emark Un|vers|ty Co||ege Iacu|ty of 1echno|ogy Department of L|ectr|ca| Lng|neer|ng, Informat|on 1echno|ogy and Cybernet|cs