Documente Academic
Documente Profesional
Documente Cultură
Thc rcsult is
emp_ae
1
z!!
/cssc:|-:9| 1ces sc| sa((c/| ||e ||||:|t c(e/c|c/ a||| ||e /|| c(||cs. (|e scme |s |/ae /c/ ||e |/t||
c(e/c|c/.
xamplc 6.46 shows thc usc ol thc XCPT sct opcrator.
XAMPL 6.46
US samplc,
SLCT cmp_no
FRM cmploycc
VHR dcpt_no - 'd3'
XCPT
SLCT cmp_no
FRM works_on
VHR cntcr_datc ~ '01.01.2008',
Thc rcsult is
emp_ae
z
z!1+
ca s|ca|1 |e cac/e ||c| ||e ||/ee se| c(e/c|c/s |c|e 1|//e/es| (/|c/|||es /c/ e|c|ac||cs. ||e ||||:|t c(e/c|c/
|cs ||e |||es| (/|c/||,, |/t|| |s e|c|ac|e1 ses|, cs1 ||e |||0| c(e/c|c/ |cs ||e |caes| (/|c/||,. |/ ,ca 1c sc| (c,
c||es||cs |c ||ese 1|//e/es| (/|c/|||es, ,ca a||| e| ases(e:|e1 /esa||s a|es ,ca ase se|e/c| se| c(e/c|c/s |ce||e/.
CAS xpressions
!n databasc application programming, it is somctimcs ncccssary to modily thc
rcprcscntation ol data. For instancc, a pcrson's gcndcr can bc codcd using thc valucs 1,
2, and 3 (lor lcmalc, malc, and child, rcspcctivcly). Such a programming tcchniquc can
Cha pt er 6 : Quer i es 165
rcducc thc timc lor thc implcmcntation ol a program. Thc CAS cxprcssion in thc
TransactSQL languagc makcs this typc ol cncoding casy to implcmcnt.
t/:| 1ces sc| /e(/eses| c s|c|emes| (cs |s mcs| (/c/cmm|s |csaces |a| cs es(/ess|cs. |e/e/c/e, ||e t/:|
es(/ess|cs :cs |e ase1 (c|mcs| e|e/,a|e/e a|e/e ||e /cssc:|-:9| |csace c||cas ||e ase c/ cs es(/ess|cs.
Thc CAS cxprcssion has two dillcrcnt lorms:
Simplc CAS cxprcssion
Scarchcd CAS cxprcssion
Thc syntax ol thc simplc CAS cxprcssion is
CAS cxprcssion_1
[VHN cxprcssion_2 THN rcsult_1] ...
|LS rcsult_n|
N
A TransactSQL statcmcnt with thc simplc CAS cxprcssion looks lor thc lirst
cxprcssion in thc list ol all VHN clauscs that match expression_1 and cvaluatcs thc
corrcsponding THN clausc. !l thcrc is no match, thc LS clausc is cvaluatcd.
Thc syntax ol thc scarchcd CAS cxprcssion is
CAS
[VHN condition_1 THN rcsult_1] ...
|LS rcsult_n|
N
A TransactSQL statcmcnt with thc scarchcd CAS cxprcssion looks lor thc lirst
cxprcssion that cvaluatcs to truc. !l nonc ol thc VHN conditions cvaluatcs to truc,
thc valuc ol thc LS cxprcssion is rcturncd. xamplc 6.47 shows thc usc ol thc
scarchcd CAS cxprcssion.
XAMPL 6.47
US samplc,
SLCT projcct_namc,
CAS
VHN budgct ~ 0 AN budgct 100000 THN 1
166 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
VHN budgct ~- 100000 AN budgct 200000 THN 2
VHN budgct ~- 200000 AN budgct 300000 THN 3
LS 4
N budgct_wcight
FRM projcct,
Thc rcsult is
pre[ect_aame hc6qet_we|qht
|je||e z
0em|a|
Mercar z
!n xamplc 6.47, budgcts ol all projccts arc wcightcd, and thc calculatcd wcights
(togcthcr with thc namc ol thc corrcsponding projcct) arc displaycd.
xamplc 6.48 shows anothcr cxamplc with thc CAS cxprcssion, whcrc thc VHN
clausc contains inncr qucrics as part ol thc cxprcssion.
XAMPL 6.48
SLCT projcct_namc,
CAS
VHN p1.budgct (SLCT A\G(p2.budgct) FRM projcct p2)
THN 'bclow avcragc'
VHN p1.budgct - (SLCT A\G(p2.budgct) FRM projcct p2)
THN 'on avcragc'
VHN p1.budgct ~ (SLCT A\G(p2.budgct) FRM projcct p2)
THN 'abovc avcragc'
N budgct_catcgory
FRM projcct p1,
Thc rcsult is
pre[ect_aame hc6qet_cateqer
|je||e |e|ew +.er+e
0em|a| |e|ew +.er+e
Mercar +|e.e +.er+e
CDMPU7 CIause
Thc CMPUT clausc uscs aggrcgatc lunctions (M!N, MAX, SUM, A\G, and
CUNT) to calculatc summary valucs that appcar as additional rows in thc rcsult
Cha pt er 6 : Quer i es 167
ol a qucry. Thc aggrcgatc lunctions uscd with thc CMPUT clausc arc rclcrrcd
to as row aggrcgatc lunctions.
Thc aggrcgatc lunctions arc usually applicd to rows ol a tablc to calculatc a scalar
valuc, which thcn appcars in thc rcsult qucry as an additional row (scc xamplc 6.49).
Thc qucry using this lorm ol aggrcgatc lunctions has, again, a row as a rcsult.
|e /esa|| c/ c t0/||| :|case |s sc| c |c||e. || |s c /e(c/|. |es:e, ||e t0/||| :|case, |s :cs|/cs| |c c|| c||e/
1es:/||e1 c(e/c|c/s cs1 :|cases, 1ces sc| |e|cs |c ||e /e|c||csc| mc1e|.
Thc CMPUT clausc has an optional 8Y option. 8Y dclincs thc grouping lorm
ol thc rcsult. !l 8Y is omittcd, thc row aggrcgatc lunction is applicd to all rows ol a
rcsult qucry. Thc option 8Y column_name spccilics that thc valucs ol thc column_
name column arc uscd to build groups. Thc RR 8Y clausc is rcquircd il thc
CMPUT clausc with 8Y is uscd.
|c sc| ase ||e t0/||| cs1 t0/||| 3 :|cases cs, mc/e, |e:case ||e, c/e mc/|e1 /c/ 1e(/e:c||cs |s ||e
ses| |e/s|cs c/ |c|c|cse |s|se. |se ||e |0|| 3 |0|||| s|c|emes| |ss|ec1 (see t|c(|e/ 1+.
xamplc 6.49 shows thc usc ol thc CMPUT clausc with thc 8Y option.
XAMPL 6.49
US samplc,
SLCT cmp_no, projcct_no, cntcr_datc
FRM works_on
VHR projcct_no - 'p1' R projcct_no - 'p2'
RR 8Y projcct_no
CMPUT M!N(cntcr_datc) 8Y projcct_no,
Thc rcsult is
emp_ae pre[ect_ae eater_6ate
z j z--
1 j zI-+-!
z!! j zI--
z1+ j zI--+
min
20061001
168 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
emp_ae pre[ect_ae eater_6ate
z!1+ jz zI-z-!
1 jz zI--
z1+ jz z-z-!
z!! jz z-z-
min
20061215
A CMPUT clausc can havc multiplc uscs in a SLCT statcmcnt. Hcncc,
xamplc 6.49 can bc writtcn using onc SLCT statcmcnt and thc lollowing
CMPUT statcmcnts:
CMPUT M!N(cntcr_datc) 8Y projcct_no
CMPUT M!N(cntcr_datc)
Thcrc arc scvcral rcstrictions conccrning thc CMPUT clausc:
SLCT !NT is not allowcd (bccausc thc rcsult ol thc CMPUT clausc is
not a tablc).
All columns in thc CMPUT clausc must appcar in a SLCT list.
RR 8Y clausc.
bc idcntical.
7emporary 7abIes
A tcmporary tablc is a databasc objcct that is tcmporarily storcd and managcd by thc
databasc systcm. Tcmporary tablcs can bc local or global. Local tcmporary tablcs havc
physical rcprcscntationthat is, thcy arc storcd in thc tempdb systcm databasc. Thcy
arc spccilicd with thc prclix # (lor cxamplc, #table_name).
A local tcmporary tablc is owncd by thc scssion that crcatcd it and is visiblc only
to that scssion. Such a tablc is thus automatically droppcd whcn thc crcating scssion
tcrminatcs. (!l you dclinc a local tcmporary tablc insidc a storcd proccdurc, it will bc
dcstroycd whcn thc corrcsponding proccdurc tcrminatcs.)
Global tcmporary tablcs arc visiblc to any uscr and any conncction altcr thcy arc
crcatcd, and arc dclctcd whcn all uscrs that arc rclcrcncing thc tablc disconncct lrom
thc databasc scrvcr. !n contrast to local tcmporary tablcs, global oncs arc spccilicd with
thc prclix ##.
Cha pt er 6 : Quer i es 169
xamplcs 6.50 and 6.51 show how thc tcmporary tablc project_temp can bc crcatcd
using two dillcrcnt TransactSQL statcmcnts.
XAMPL 6.50
US samplc,
CRAT TA8L #projcct_tcmp
(projcct_no CHAR(4) NT NULL,
projcct_namc CHAR(25) NT NULL),
XAMPL 6.51
US samplc,
SLCT projcct_no, projcct_namc
!NT #projcct_tcmp
FRM projcct,
xamplcs 6.50 and 6.51 arc similar. Thcy usc two dillcrcnt TransactSQL statcmcnts
to crcatc thc local tcmporary tablc #project_temp. Howcvcr, xamplc 6.50 actually
populatcs thc tcmporary tablc with thc data lrom thc project tablc, whilc xamplc 6.51
lcavcs it cmpty.
1oin Dperator
Thc prcvious scctions ol this chaptcr dcmonstratcd thc usc ol thc SLCT statcmcnt
to qucry rows lrom onc tablc ol a databasc. !l thc TransactSQL languagc supportcd
only such simplc SLCT statcmcnts, thc attachmcnt ol two or morc tablcs to rctricvc
data would not bc possiblc. Conscqucntly, all data ol a databasc would havc to bc
storcd in onc tablc. Although thc storagc ol all thc data ol a databasc insidc onc tablc is
possiblc, it has onc main disadvantagcthc storcd data arc highly rcdundant.
TransactSQL providcs thc join opcrator, which rctricvcs data lrom morc than onc
tablc. This opcrator is probably thc most important opcrator lor rclational databasc
systcms, bccausc it allows data to bc sprcad ovcr many tablcs and thus achicvcs a vital
propcrty ol databasc systcmsnonrcdundant data.
|e |||0| c(e/c|c/ c|sc c||c:|es |ac c/ mc/e |c||es. |cae|e/, ||e |||0| c(e/c|c/ c|ac,s c||c:|es |ac c/
mc/e :|||t s|c|emes|s, a|||e ||e (c|s c(e/c|c/ (c|ss |ac c/ mc/e |c||es as|s (as| cse :|||t. |a/||e/, ||e
|||0| c(e/c|c/ c||c:|es /cas c/ |c||es, a|||e, cs ,ca a||| see |c|e/ |s |||s se:||cs, ||e (c|s c(e/c|c/ (c|ss
:c|amss c/ |c||es.
170 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Thc join opcrator is applicd to basc tablcs and vicws. !n this chaptcr, joins bctwccn
basc tablcs arc discusscd, whilc joins conccrning vicws will bc discusscd in Chaptcr 11.
Thcrc arc scvcral dillcrcnt lorms ol thc join opcrator. This scction discusscs thc
lollowing lundamcntal typcs:
Natural join
Cartcsian product (cross join)
utcr join
8clorc cxplaining dillcrcnt join lorms, this scction dcscribcs thc dillcrcnt syntax
lorms ol thc join opcrator.
7wo Syntax Forms to ImpIement 1oins
To join tablcs, you can usc two dillcrcnt lorms:
xplicit join syntax (ANS! SQL :1992 join syntax)
!mplicit join syntax (old stylc join syntax)
Thc ANS! SQL:1992 join syntax is introduccd in thc SQL92 standard and dclincs
join opcrations cxplicitlythat is, using thc corrcsponding namc lor cach typc ol thc
join opcration. Thc kcywords conccrning thc cxplicit dclinition ol join arc
CRSS J!N
|!NNR| J!N
LFT |UTR| J!N
R!GHT |UTR| J!N
FULL |UTR| J!N
CRSS J!N spccilics thc Cartcsian product ol two tablcs. !NNR J!N dclincs
thc natural join ol two tablcs, whilc LFT UTR J!N and R!GHT UTR
J!N charactcrizc thc join opcrations ol thc samc namcs, rcspcctivcly. Finally, FULL
UTR J!N spccilics thc union ol thc right and lclt outcr joins. (All thcsc dillcrcnt
join opcrations arc cxplaincd in thc lollowing scctions.)
Thc implicit join syntax is "oldstylc" syntax, whcrc cach join opcration is dclincd
implicitly via thc VHR clausc, using thc socallcd join columns (scc xamplc 6.52).
Cha pt er 6 : Quer i es 171
|se c/ ||e es(||:|| (c|s s,s|cs |s /e:cmmes1e1. ||s s,s|cs es|cs:es ||e /ec1c|||||, c/ ae/|es. |c/ |||s /ecscs,
c|| escm(|es |s |||s :|c(|e/ :cs:e/s|s ||e (c|s c(e/c||cs c/e sc||e1 as|s ||e es(||:|| s,s|cs /c/ms. |s c /ea
|s|/c1a:|c/, escm(|es, ,ca a||| see ||e c|1-s|,|e s,s|cs, |cc.
NaturaI 1oin
Natural join is bcst cxplaincd through thc usc ol an cxamplc, so chcck out xamplc 6.52.
|e (|/cses sc|a/c| (c|s cs1 ea|-(c|s c/e c/|es ase1 cs s,scs,ms, |a| ||e/e |s c s|||| 1|//e/es:e |e|aees
||em. |s ||e ea|-(c|s c(e/c||cs, ||e/e |s c|ac,s cse c/ mc/e (c|/s c/ :c|amss ||c| |c|e |1es||:c| |c|aes |s e|e/,
/ca. |e c(e/c||cs ||c| e||m|sc|es sa:| :c|amss //cm ||e ea|-(c|s |s :c||e1 c sc|a/c| (c|s.
XAMPL 6.52
Gct lull dctails ol cach cmploycc, that is, bcsidcs thc cmploycc's numbcr, lirst and
last namcs, and corrcsponding dcpartmcnt numbcr, also gct thc namc ol his or hcr
dcpartmcnt and its location, with duplicatc columns displaycd.
xplicit join syntax:
US samplc,
SLCT cmploycc., dcpartmcnt.
FRM cmploycc !NNR J!N dcpartmcnt
N cmploycc.dcpt_no - dcpartmcnt.dcpt_no,
Thc SLCT list in xamplc 6.52 includcs all columns ol thc employee and
department tablcs. Thc FRM clausc in thc SLCT statcmcnt spccilics thc tablcs
that arc joincd as wcll as thc cxplicit namc ol thc join lorm (!NNR J!N). Thc N
clausc is also part ol thc FRM clausc, it spccilics thc join columns lrom both tablcs.
Thc condition cmploycc.dcpt_no - dcpartmcnt.dcpt_no in xamplc 6.52 spccilics a
join condition, and both columns arc said to bc join columns.
Thc cquivalcnt solution is as lollows:
"ldstylc" join syntax:
US samplc,
SLCT cmploycc., dcpartmcnt.
FRM cmploycc, dcpartmcnt
VHR cmploycc.dcpt_no - dcpartmcnt.dcpt_no,
172 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Thc "oldstylc" join syntax contains two signilicant dillcrcnccs: thc FRM clausc
ol thc qucry contains thc list ol tablcs that arc joincd, and thc corrcsponding join
condition is spccilicd in thc VHR clausc using join columns.
Thc rcsult is
emp_ae emp_faame emp_|aame 6ept_ae 6ept_ae 6ept_aame |ecat|ea
z!1+ M+tt|ew :m|t| a1 a1 M+r|et|a |+||+.
z |aa Ieae. a1 a1 M+r|et|a |+||+.
1 Ie|a |+rr|mere a a |e.e+rc| |+||+.
z1+ I+me. I+me. az az |cceaat|a :e+tt|e
1 ||.+ |ertea| az az |cceaat|a :e+tt|e
z! |||e |+a.e| az az |cceaat|a :e+tt|e
z!! :|||| Me.er a a |e.e+rc| |+||+.
|| |s s|/cs|, /e:cmmes1 ||c| ,ca ase |s c :|||t ||s| cs|, a|es ,ca c/e as|s |s|e/c:|||e :9|, cs1 c|c|1 ||s
ase |s cs c((||:c||cs (/c/cm.
xamplc 6.52 can bc uscd to show how a join opcration works. Notc that this is just
an illustration ol how you can think about thc join proccss, atabasc nginc actually
has scvcral stratcgics lrom which it chooscs to implcmcnt thc join opcrator. !maginc
cach row ol thc employee tablc combincd with cach row ol thc department tablc. Thc
rcsult ol this combination is a tablc with 7 columns (4 lrom thc tablc employee and 3
lrom thc tablc department) and 21 rows (scc Tablc 61).
!n thc sccond stcp, all rows lrom Tablc 61 that do not satisly thc join condition
cmploycc.dcpt_no - dcpartmcnt.dcpt_no arc rcmovcd. Thcsc rows arc prclixcd in
Tablc 61 with thc * sign. Thc rcst ol thc rows rcprcscnt thc rcsult ol xamplc 6.52.
Thc scmantics ol thc corrcsponding join columns must bc idcntical. This mcans both
columns must havc thc samc logical mcaning. !t is not rcquircd that thc corrcsponding
join columns havc thc samc namc (or cvcn an idcntical typc), although this will oltcn
bc thc casc.
|| |s sc| (css|||e /c/ c 1c|c|cse s,s|em |c :|e:| ||e |c|:c| mecs|s c/ c :c|ams. (|c/ |ss|cs:e, (/c(e:| sam|e/
cs1 em(|c,ee sam|e/ |c|e sc|||s |s :cmmcs, c|||ca| |c|| :c|amss c/e 1e/|se1 cs |s|ee/s. |e/e/c/e,
1c|c|cse s,s|ems :cs cs|, :|e:| ||e 1c|c |,(e cs1 ||e |es|| c/ s|/|s 1c|c |,(es. |c|c|cse |s|se /ea|/es
||c| ||e :c//es(cs1|s (c|s :c|amss |c|e :cm(c||||e 1c|c |,(es, sa:| cs || cs1 ://||||.
Cha pt er 6 : Quer i es 173
Thc sample databasc contains thrcc pairs ol columns in which cach column ol
thc pair has thc samc logical mcaning (and thcy havc thc samc namcs as wcll). Thc
employee and department tablcs can bc joincd using thc columns employee.dept_no
and department.dept_no. Thc join columns ol thc employee and works_on tablcs
arc thc columns employee.emp_no and works_on.emp_no. Finally, thc project and
works_on tablcs can bc joincd using thc join columns project.project_no and works_
on.project_no.
Thc namcs ol columns in a SLCT statcmcnt can bc qualilicd. "Qualilying"
a column namc mcans that, to avoid any possiblc ambiguity about which tablc thc
column bclongs to, thc column namc is prcccdcd by its tablc namc (or thc alias ol thc
tablc), scparatcd by a pcriod: table_name.column_name.
emp_ae emp_faame emp_|aame 6ept_ae 6ept_ae 6ept_aame |ecat|ea
z!1+ M+tt|ew :m|t| a1 a |e.e+rc| |+||+.
z |aa Ieae. a1 a |e.e+rc| |+||+.
1 Ie|a |+rr|mere a a |e.e+rc| |+||+.
z1+ I+me. I+me. az a |e.e+rc| |+||+.
1 ||.+ |ertea| az a |e.e+rc| |+||+.
z! |||e |+a.e| az a |e.e+rc| |+||+.
z!! :|||| Me.er a a |e.e+rc| |+||+.
z!1+ M+tt|ew :m|t| a1 az |cceaat|a :e+tt|e
z |aa Ieae. a1 az |cceaat|a :e+tt|e
1 Ie|a |+rr|mere a az |cceaat|a :e+tt|e
z1+ I+me. I+me. az az |cceaat|a :e+tt|e
1 ||.+ |ertea| az az |cceaat|a :e+tt|e
z! |||e |+a.e| az az |cceaat|a :e+tt|e
z!! :|||| Me.er a az |cceaat|a :e+tt|e
z!1+ M+tt|ew :m|t| a1 a1 M+r|et|a |+||+.
z |aa Ieae. a1 a1 M+r|et|a |+||+.
1 Ie|a |+rr|mere a a1 M+r|et|a |+||+.
z1+ I+me. I+me. az a1 M+r|et|a |+||+.
1 ||.+ |ertea| az a1 M+r|et|a |+||+.
z! |||e |+a.e| az a1 M+r|et|a |+||+.
z!! :|||| Me.er a a1 M+r|et|a |+||+.
Iah|e 6-1 |esa|| c/ ||e tc/|es|cs |/c1a:| 3e|aees ||e c||es em(|c,ee cs1 1e(c/|mes|
174 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
!n most SLCT statcmcnts a column namc docs not nccd any qualilication,
although thc usc ol qualilicd namcs is gcncrally rccommcndcd lor rcadability. !l column
namcs within a SLCT statcmcnt arc ambiguous (likc thc columns employee.dept_
no and department.dept_no in xamplc 6.52), thc qualilicd namcs lor thc columns
must bc uscd.
!n a SLCT statcmcnt with a join, thc VHR clausc can includc othcr
conditions in addition to thc join condition, as shown in xamplc 6.53.
XAMPL 6.53
Gct lull dctails ol all cmployccs who work on thc projcct Gcmini.
xplicit join syntax:
US samplc,
SLCT cmp_no, projcct.projcct_no, job, cntcr_datc, projcct_namc, budgct
FRM works_on J!N projcct
N projcct.projcct_no - works_on.projcct_no
VHR projcct_namc - 'Gcmini',
"ldstylc" join syntax:
US samplc,
SLCT cmp_no, projcct.projcct_no, job, cntcr_datc, projcct_namc, budgct
FRM works_on, projcct
VHR projcct.projcct_no - works_on.projcct_no
AN projcct_namc - 'Gcmini',
|e ac||/|:c||cs c/ ||e :c|amss , , , cs1 |s |scm(|e .:? |s sc| se:essc/,,
|e:case ||e/e |s sc cm||a||, /ec/1|s ||ese scmes.
Thc rcsult is
emp_ae pre[ect_ae [eh eater_6ate pre[ect_aame hc6qet
z!1+ jz C|er| zI-z-! 0em|a| !.
1 jz NJ|| zI-- 0em|a| !.
z1+ jz NJ|| z-z-! 0em|a| !.
z!! jz C|er| z-z- 0em|a| !.
Cha pt er 6 : Quer i es 175
From this point lorward, all cxamplcs will bc implcmcntcd using thc cxplicit join
syntax only.
xamplc 6.54 shows anothcr usc ol thc inncr join.
XAMPL 6.54
Gct thc dcpartmcnt numbcr lor all cmployccs who cntcrcd thcir projccts on ctobcr 15,
2007:
US samplc,
SLCT dcpt_no
FRM cmploycc J!N works_on
N cmploycc.cmp_no - works_on.cmp_no
VHR cntcr_datc - '10.15.2007',
Thc rcsult is
6ept_ae
az
1oining More 7han 7wo 7abIes
Thcorctically, thcrc is no uppcr limit on thc numbcr ol tablcs that can bc joincd using
a SLCT statcmcnt. (nc join condition always combincs two tablcs!) Howcvcr,
atabasc nginc has an implcmcntation rcstriction: thc maximum numbcr ol tablcs
that can bc joincd in a SLCT statcmcnt is 64.
|sac||,, c mcs|mam c/ e||| |c |es |c||es c/e (c|se1 |s c :|||t s|c|emes|. |/ ,ca see1 |c (c|s mc/e ||cs |es
|c||es |s c :|||t s|c|emes|, ,ca/ 1c|c|cse 1es|s |s (/c|c||, sc| c(||mc|.
xamplc 6.55 joins thrcc tablcs ol thc sample databasc.
XAMPL 6.55
Gct thc lirst and last namcs ol all analysts whosc dcpartmcnt is locatcd in Scattlc:
US samplc,
SLCT cmp_lnamc, cmp_lnamc
FRM works_on J!N cmploycc N works_on.cmp_no-cmploycc.cmp_no
J!N dcpartmcnt N cmploycc.dcpt_no-dcpartmcnt.dcpt_no
AN location - 'Scattlc'
AN job - 'analyst',
176 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Thc rcsult is
emp_faame emp_|aame
|||e |+a.e|
Thc rcsult in xamplc 6.55 can bc obtaincd only il you join at lcast thrcc tablcs:
works_on, employee, and department. Thcsc tablcs can bc joincd using two pairs ol
join columns:
(works_on.cmp_no, cmploycc.cmp_no)
(cmploycc.dcpt_no,dcpartmcnt.dcpt_no)
xamplc 6.56 uscs all lour tablcs lrom thc sample databasc to obtain thc rcsult sct.
XAMPL 6.56
Gct thc namcs ol projccts (with rcdundant duplicatcs climinatcd) bcing workcd on by
cmployccs in thc Accounting dcpartmcnt:
US samplc,
SLCT !ST!NCT projcct_namc
FRM projcct J!N works_on
N projcct.projcct_no - works_on.projcct_no
J!N cmploycc N works_on.cmp_no - cmploycc.cmp_no
J!N dcpartmcnt N cmploycc.dcpt_no - dcpartmcnt.dcpt_no
VHR dcpt_namc - 'Accounting',
Thc rcsult is
pre[ect_aame
|je||e
0em|a|
Mercar
Noticc that whcn joining thrcc tablcs, you usc two join conditions (linking two
tablcs cach) to achicvc a natural join. Vhcn you join lour tablcs, you usc thrcc such
join conditions. !n gcncral, il you join n tablcs, you nccd n 1 join conditions to
avoid a Cartcsian product. l coursc, morc than n 1 join conditions, as wcll as othcr
conditions, arc ccrtainly pcrmissiblc to lurthcr rcducc thc rcsult sct.
Cha pt er 6 : Quer i es 177
Cartesian Product
Thc prcvious scction illustratcd a possiblc mcthod ol producing a natural join. !n thc
lirst stcp ol this proccss, cach row ol thc employee tablc is combincd with cach row
ol thc department tablc. This intcrmcdiatc rcsult was madc by thc opcration callcd
Cartcsian product. xamplc 6.57 shows thc Cartcsian product ol thc tablcs employee
and department.
XAMPL 6.57
US samplc,
SLCT cmploycc., dcpartmcnt.
FRM cmploycc CRSS J!N dcpartmcnt,
Thc rcsult ol xamplc 6.57 is shown in Tablc 61. A Cartcsian product combincs
cach row ol thc lirst tablc with cach row ol thc sccond onc. !n gcncral, thc Cartcsian
product ol two tablcs such that thc lirst tablc has n rows and thc sccond tablc has m
rows will producc a rcsult with n timcs m rows (or nm). Thus, thc rcsult sct in
xamplc 6.57 contains 73 - 21 rows.
!n practicc, thc usc ol a Cartcsian product is highly unusual. Somctimcs uscrs
gcncratc thc Cartcsian product ol two tablcs whcn thcy lorgct to includc thc join
condition in thc VHR clausc ol thc "oldstylc" join syntax. !n this casc, thc output
docs not corrcspond to thc cxpcctcd rcsult bccausc it contains too many rows. (Thc
cxistcncc ol many and uncxpcctcd rows in thc rcsult is a hint that a Cartcsian product
ol two tablcs, rathcr than thc intcndcd natural join, has bccn produccd.)
Duter 1oin
!n thc prcvious cxamplcs ol natural join, thc rcsult sct includcd only rows lrom onc
tablc that havc corrcsponding rows in thc othcr tablc. Somctimcs it is ncccssary to
rctricvc, in addition to thc matching rows, thc unmatchcd rows lrom onc or both ol thc
tablcs. Such an opcration is callcd an outer join.
xamplcs 6.58 and 6.59 show thc dillcrcncc bctwccn a natural join and thc
corrcsponding outcr join. (All cxamplcs in this scction usc thc employee_enh tablc.)
XAMPL 6.58
Gct lull dctails ol all cmployccs, including thc location ol thcir dcpartmcnt, who livc
and work in thc samc city.
US samplc,
SLCT cmploycc_cnh., dcpartmcnt.location
FRM cmploycc_cnh J!N dcpartmcnt
N domicilc - location,
178 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Thc rcsult is
emp_ae emp_faame emp_|aame 6ept_ae 6em|c||e |ecat|ea
z1+ I+me. I+me. az :e+tt|e :e+tt|e
xamplc 6.58 uscs a natural join to display thc rcsult sct ol rows. !l you would likc
to know all othcr cxisting living placcs ol cmployccs, you havc to usc thc (lclt) outcr
join. This is callcd a left outcr join bccausc all rows lrom thc tablc on thc left sidc ol thc
opcrator arc rcturncd, whcthcr or not thcy havc a matching row in thc tablc on thc right.
!n othcr words, il thcrc arc no matching rows in thc tablc on thc right sidc, thc outcr
join will still rcturn a row lrom thc tablc on thc lclt sidc, with NULL in cach column ol
thc othcr tablc (scc xamplc 6.59). atabasc nginc uscs thc opcrator LFT UTR
J!N to spccily thc lclt outcr join.
A right outcr join is similar, but it rcturns all rows ol thc tablc on thc right ol thc
symbol. atabasc nginc uscs thc opcrator R!GHT UTR J!N to spccily thc
right outcr join.
XAMPL 6.59
Gct lull dctails lor all cmployccs plus locations ol thcir dcpartmcnts, lor all citics that
arc cithcr thc living placcs, or both living and working placcs, ol cmployccs:
US samplc,
SLCT cmploycc_cnh., dcpartmcnt.location
FRM cmploycc_cnh LFT UTR J!N dcpartmcnt
N domicilc - location,
Thc rcsult is
emp_ae emp_faame emp_|aame 6ept_ae 6em|c||e |ecat|ea
z!1+ M+tt|ew :m|t| a1 :+a |atea|e NJ||
z |aa Ieae. a1 |ea.tea NJ||
1 Ie|a |+rr|mere a :+a |atea|e NJ||
z1+ I+me. I+me. az :e+tt|e :e+tt|e
1 ||.+ |ertea| az |ert|+aa NJ||
z! |||e |+a.e| az I+cem+ NJ||
z!! :|||| Me.er a |ea.tea NJ||
Cha pt er 6 : Quer i es 179
As you can scc, whcn thcrc is no matching row in thc tablc on thc right sidc
(department, in this casc), thc lclt outcr join still rcturns thc rows lrom thc tablc on
thc lclt sidc (employee_enh), and thc columns ol thc othcr tablc arc populatcd by
NULL valucs. xamplc 6.60 shows thc usc ol thc right outcr join opcration.
XAMPL 6.60
Gct lull dctails ol all dcpartmcnts, as wcll as all living placcs ol thcir cmployccs, lor all
citics that arc cithcr thc locations ol dcpartmcnts or thc living and working placcs ol an
cmploycc.
US samplc,
SLCT cmploycc_cnh.domicilc, dcpartmcnt.
FRM cmploycc_cnh R!GHT UTR J!N dcpartmcnt
N domicilc -location,
Thc rcsult is
6em|c||e 6ept_ae 6ept_aame |ecat|ea
:e+tt|e az |cceaat|a :e+tt|e
NJ|| a |e.e+rc| |+||+.
NJ|| a1 M+r|et|a |+||+.
!n addition to thc lclt and right outcr joins, thcrc is also thc lull outcr join, which is
dclincd as thc union ol thc lclt and right outcr joins. !n othcr words, all rows lrom both
tablcs arc rcprcscntcd in thc rcsult sct. !l thcrc is no corrcsponding row in onc ol thc
tablcs, its columns arc rcturncd with NULL valucs. This opcration is spccilicd using thc
FULL UTR J!N opcrator.
atabasc nginc supports thc proprictary syntax lor lclt and right outcr joins, *= and
=*, only undcr a backwardcompatibility llag. To cnablc this nonstandard syntax, you havc
to changc thc databasc's compatibility modc to that ol SQL Scrvcr 2000, which is 80.
t|cs|s ||e :cm(c|||||||, mc1e |s sc| /e:cmmes1e1 |e:case ,ca :cssc| ase cs, sea /ec|a/es //cm
||e /c||ca|s |e/s|css. |c/ |||s /ecscs, |/ ,ca acs| |c |m(|emes| cs, ||s1 c/ ca|e/ (c|s, ase ||e s|cs1c/1|ce1
(c|s s,s|cs.
vcry outcr join opcration can bc simulatcd using thc UN!N opcrator plus thc
NT X!STS lunction. xamplc 6.61 is cquivalcnt to thc cxamplc with thc lclt outcr
join (xamplc 6.59).
180 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
XAMPL 6.61
Gct lull dctails lor all cmployccs, plus locations ol thcir dcpartmcnts, lor all citics that
arc cithcr thc living placcs, or both living and working placcs, ol cmployccs:
US samplc,
SLCT cmploycc_cnh., dcpartmcnt.location
FRM cmploycc_cnh J!N dcpartmcnt
N domicilc - location
UN!N
SLCT cmploycc_cnh., 'NULL'
FRM cmploycc_cnh
VHR NT X!STS
(SLCT
FRM dcpartmcnt
VHR location - domicilc),
Thc lirst SLCT statcmcnt in thc union spccilics thc natural join ol thc tablcs
employee_enh and department with thc join columns domicile and location. This
SLCT statcmcnt rctricvcs all citics that arc at thc samc timc thc living placcs
and working placcs ol cach cmploycc. Thc sccond SLCT statcmcnt in thc union
rctricvcs, additionally, all rows lrom thc employee_enh tablc that do not match thc
condition in thc natural join.
Furtber Forms of 1oin Dperations
Thc prcccding scctions discusscd thc most important join lorms. This scction shows
you thrcc othcr lorms:
Sclljoin
Scmijoin
Thc lollowing subscctions dcscribc thcsc lorms.
7heta 1oin
Join columns nccd not bc comparcd using thc cquality sign. A join opcration using a
gcncral join conditionthat is, using a comparison opcrator othcr than cqualityis
callcd a thcta join. xamplc 6.62, which uscs thc employee_enh tablc, shows thc thcta
join opcration.
Cha pt er 6 : Quer i es 181
XAMPL 6.62
Gct all thc combinations ol cmploycc inlormation and dcpartmcnt inlormation whcrc
thc domicilc ol an cmploycc alphabctically prcccdcs thc location ol thc dcpartmcnt, in
which that cmploycc works.
US samplc,
SLCT cmp_lnamc, cmp_lnamc, domicilc, location
FRM cmploycc_cnh J!N dcpartmcnt
N domicilc location,
Thc rcsult is
emp_faame emp_|aame 6em|c||e |ecat|ea
M+tt|ew :m|t| :+a |atea|e :e+tt|e
|aa Ieae. |ea.tea :e+tt|e
Ie|a |+rr|mere :+a |atea|e :e+tt|e
||.+ |ertea| |ert|+aa :e+tt|e
:|||| Me.er |ea.tea :e+tt|e
!n xamplc 6.62, thc corrcsponding valucs ol columns domicile and location
arc comparcd. !n cvcry rcsulting row, thc valuc ol thc domicile column is ordcrcd
alphabctically bclorc thc corrcsponding valuc ol thc location column.
SeIf-1oin, or 1oining a 7abIe with ItseIf
!n addition to joining two or morc dillcrcnt tablcs, a natural join opcration can also
bc applicd to a singlc tablc. !n this casc, thc tablc is joincd with itscll, whcrcby a singlc
column ol thc tablc is comparcd with itscll. Thc comparison ol a column with itscll
mcans that thc tablc namc appcars twicc in thc FRM clausc ol a SLCT statcmcnt.
Thcrclorc, you nccd to bc ablc to rclcrcncc thc namc ol thc samc tablc twicc. This can
bc accomplishcd using at lcast onc alias namc. Thc samc is truc lor thc column namcs in
thc join condition ol a SLCT statcmcnt. !n ordcr to distinguish both column namcs,
you usc thc qualilicd namcs. xamplc 6.63 joins thc department tablc with itscll.
XAMPL 6.63
Gct lull dctails ol all dcpartmcnts locatcd at thc samc location as at lcast onc othcr
dcpartmcnt:
US samplc,
SLCT t1.dcpt_no, t1.dcpt_namc, t1.location
182 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
FRM dcpartmcnt t1 J!N dcpartmcnt t2
N t1.location - t2.location
VHR t1.dcpt_no ~ t2.dcpt_no,
Thc rcsult is
6ept_ae 6ept_aame |ecat|ea
a1 M+r|et|a |+||+.
a |e.e+rc| |+||+.
Thc FRM clausc in xamplc 6.63 contains two aliascs lor thc department tablc:
t1 and t2. Thc lirst condition in thc VHR clausc spccilics thc join columns, whilc
thc sccond condition climinatcs unncccssary duplicatcs by making ccrtain that cach
dcpartmcnt is comparcd with different dcpartmcnts.
Semi-1oin
Thc scmijoin is similar to thc natural join, but thc rcsult ol thc scmijoin is only thc
sct ol all rows lrom onc tablc whcrc onc or morc matchcs arc lound in thc sccond tablc.
xamplc 6.64 shows thc scmijoin opcration.
XAMPL 6.64
US samplc,
SLCT cmp_no, cmp_lnamc, c.dcpt_no
FRM cmploycc c J!N dcpartmcnt d
N c.dcpt_no - d.dcpt_no
VHR location - 'allas',
Thc rcsult is
emp_ae emp_|aame 6ept_ae
z!1+ :m|t| a1
z Ieae. a1
1 |+rr|mere a
z!! Me.er a
As can bc sccn lrom xamplc 6.64, thc SLCT list ol thc scmijoin contains
only columns lrom thc employee tablc. This is cxactly what charactcrizc thc scmijoin
opcration. This opcration is usually uscd in distributcd qucry proccssing to minimizc
data translcr. atabasc nginc uscs thc scmijoin opcration to implcmcnt thc lcaturc
callcd star join (scc Chaptcr 26).
Cha pt er 6 : Quer i es 183
CorreIated Subqueries
A subqucry is said to bc a correlated subquery il thc inncr qucry dcpcnds on thc outcr
qucry lor any ol its valucs. xamplc 6.65 shows a corrclatcd subqucry.
XAMPL 6.65
Gct thc last namcs ol all cmployccs who work on projcct p3:
US samplc,
SLCT cmp_lnamc
FRM cmploycc
VHR 'p3' !N
(SLCT projcct_no
FRM works_on
VHR works_on.cmp_no - cmploycc.cmp_no),
Thc rcsult is
emp_|aame
Ieae.
|ertea|
|+a.e|
Thc inncr qucry in xamplc 6.65 must bc logically cvaluatcd many timcs bccausc it
contains thc emp_no column, which bclongs to thc employee tablc in thc outcr qucry,
and thc valuc ol thc emp_no column changcs cvcry timc atabasc nginc cxamincs a
dillcrcnt row ol thc employee tablc in thc outcr qucry.
Lct's walk through how thc systcm might proccss thc qucry in xamplc 6.65. First, thc
systcm rctricvcs thc lirst row ol thc employee tablc (lor thc outcr qucry) and comparcs
thc cmploycc numbcr ol that column (25348) with valucs ol thc works_on.emp_no
column in thc inncr qucry. Sincc thc only project_no lor this cmploycc is p2, thc inncr
qucry rcturns thc valuc p2. Thc singlc valuc in thc sct is not cqual to thc constant valuc p3
in thc outcr qucry, so thc outcr qucry's condition (VHR 'p3' !N .) is not mct and
no rows arc rcturncd by thc outcr qucry lor this cmploycc. Thcn, thc systcm rctricvcs
thc ncxt row ol thc employee tablc and rcpcats thc comparison ol cmploycc numbcrs in
both tablcs. Thc sccond cmploycc has two rows in thc works_on tablc with project_no
valucs ol p1 and p3, so thc rcsult sct ol thc inncr qucry is (p1,p3). nc ol thc clcmcnts
in thc rcsult sct is cqual to thc constant valuc p3, so thc condition is cvaluatcd to truc
and thc corrcsponding valuc ol thc emp_lname column in thc sccond row ( Joncs) is
184 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
displaycd. Thc samc proccss is applicd to all rows ol thc employee tablc, and thc linal
rcsult sct with thrcc rows is rctricvcd.
Morc cxamplcs ol corrclatcd subqucrics arc shown in thc ncxt scction.
Subqueries and tbe XIS7S Function
Thc X!STS lunction takcs an inncr qucry as an argumcnt and rcturns truc il thc inncr
qucry rcturns onc or morc rows, and rcturns lalsc il it rcturns zcro rows. This lunction
will bc cxplaincd using cxamplcs.
XAMPL 6.66
Gct thc last namcs ol all cmployccs who work on projcct p1:
US samplc,
SLCT cmp_lnamc
FRM cmploycc
VHR X!STS
(SLCT
FRM works_on
VHR cmploycc.cmp_no - works_on.cmp_no
AN projcct_no - 'p1'),
Thc rcsult is
emp_|aame
Ieae.
I+me.
|ertea|
Me.er
Thc inncr qucry ol thc X!STS lunction almost always dcpcnds on a variablc lrom
an outcr qucry. Thcrclorc, thc X!STS lunction usually spccilics a corrclatcd subqucry.
Lct's walk through how atabasc nginc might proccss thc qucry in xamplc 6.66.
First, thc outcr qucry considcrs thc lirst row ol thc employee tablc (Smith). Ncxt, thc
X!STS lunction is cvaluatcd to dctcrminc whcthcr thcrc arc any rows in thc works_on
tablc whosc cmploycc numbcr matchcs thc onc lrom thc currcnt row in thc outcr qucry,
and whosc project_no is p1. 8ccausc Mr. Smith docs not work on thc projcct p1, thc
rcsult ol thc inncr qucry is an cmpty sct and thc X!STS lunction is cvaluatcd to lalsc.
Thcrclorc, thc cmploycc namcd Smith docs not bclong to thc linal rcsult sct. Using this
proccss, all rows ol thc employee tablc arc tcstcd, and thc rcsult sct is displaycd.
xamplc 6.67 shows thc usc ol thc NT X!STS lunction.
Cha pt er 6 : Quer i es 185
XAMPL 6.67
Gct thc last namcs ol all cmployccs who work lor dcpartmcnts not locatcd in Scattlc:
US samplc,
SLCT cmp_lnamc
FRM cmploycc
VHR NT X!STS
(SLCT
FRM dcpartmcnt
VHR cmploycc.dcpt_no - dcpartmcnt.dcpt_no
AN location - 'Scattlc'),
Thc rcsult is
emp_|aame
:m|t|
Ieae.
|+rr|mere
Me.er
Thc SLCT list ol an outcr qucry involving thc X!STS lunction is not rcquircd
to bc ol thc lorm SLCT as in thc prcvious cxamplcs. Thc lorm SLCT column_
list, whcrc column_list is onc or morc columns ol thc tablc, is an altcrnatc lorm.
8oth lorms arc cquivalcnt, bccausc thc X!STS lunction tcsts only thc cxistcncc (i.c.,
noncxistcncc) ol rows in thc rcsult sct. For this rcason, thc usc ol SLCT in this
casc is salc.
SbouId You Use 1oins or Subqueries!
Almost all SLCT statcmcnts that join tablcs and usc thc join opcrator can bc
rcwrittcn as subqucrics and vicc vcrsa. Vriting thc SLCT statcmcnt using thc join
opcrator is oltcn casicr to rcad and undcrstand and can also hclp atabasc nginc to
lind a morc cllicicnt stratcgy lor rctricving thc appropriatc data. Howcvcr, thcrc arc a
lcw problcms that can bc casicr solvcd using subqucrics, and thcrc arc othcrs that can
bc casicr solvcd using joins.
Subquery Advantages
Subqucrics arc advantagcous ovcr joins whcn you havc to calculatc an aggrcgatc valuc
on thc lly and usc it in thc outcr qucry lor comparison. xamplc 6.68 shows this.
186 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
XAMPL 6.68
Gct thc cmploycc numbcrs and cntcr datcs ol all cmployccs with cntcr datcs cqual to
thc carlicst datc:
US samplc
SLCT cmp_no, cntcr_datc
FRM works_on
VHR cntcr_datc - (SLCT min(cntcr_datc)
FRM works_on)
This problcm cannot bc solvcd casily with a join, bccausc you would havc to writc
thc aggrcgatc lunction in thc VHR clausc and it is not allowcd. (You can solvc thc
problcm using two scparatc qucrics in rclation to thc works_on tablc.)
1oin Advantages
Joins arc advantagcous ovcr subqucrics il thc SLCT list in a qucry contains columns
lrom morc than onc tablc. xamplc 6.69 shows this.
XAMPL 6.69
Gct thc cmploycc numbcrs, last namcs, and jobs lor all cmployccs that cntcrcd thcir
projccts on ctobcr 15, 2007:
US samplc,
SLCT cmploycc.cmp_no, cmp_lnamc, job
FRM cmploycc, works_on
VHR cmploycc.cmp_no - works_on.cmp_no
AN cntcr_datc - '10.15.2007',
Thc SLCT list ol thc qucry in xamplc 6.69 contains columns emp_no and
emp_lname lrom thc employee tablc and thc job column lrom thc works_on tablc.
For this rcason, thc cquivalcnt solution with thc subqucry would display an crror,
bccausc subqucrics can display inlormation only lrom thc outcr tablc.
7abIe xpressions
Tablc cxprcssions arc subqucrics that arc uscd whcrc a tablc is cxpcctcd. Thcrc arc two
typcs ol tablc cxprcssions:
crivcd tablcs
Common tablc cxprcssions
Cha pt er 6 : Quer i es 187
Thc lollowing subscctions dcscribc thcsc two lorms ol tablc cxprcssions.
Derived 7abIes
A dcrivcd tablc is a tablc cxprcssion that appcars in thc FRM clausc ol a qucry. You
can apply dcrivcd tablcs whcn thc usc ol column aliascs is not possiblc bccausc anothcr
clausc is proccsscd by thc SQL translator bclorc thc alias namc is known. xamplc 6.70
shows an attcmpt to usc a column alias whcrc anothcr clausc is proccsscd bclorc thc
alias namc is known.
XAMPL 6.70 (XAMPL DF AN ILLCAL S7A7MN7)
Gct all cxisting groups ol months lrom thc enter_date column ol thc works_on tablc:
US samplc,
SLCT MNTH(cntcr_datc) as cntcr_month
FRM works_on
GRUP 8Y cntcr_month,
Thc rcsult is
Mcssagc 207: Lcvcl 16, Statc 1, Linc 4
Thc invalid column 'cntcr_month'
Thc rcason lor thc crror mcssagc is that thc GRUP 8Y clausc is proccsscd bclorc
thc corrcsponding SLCT list, and thc alias namc enter_month is not known at thc
timc thc grouping is proccsscd.
8y using a dcrivcd tablc that contains thc prcccding qucry (without thc GRUP 8Y
clausc), you can solvc this problcm, bccausc thc FRM clausc is cxccutcd bclorc thc
GRUP 8Y clausc, as shown in xamplc 6.71.
XAMPL 6.71
US samplc,
SLCT cntcr_month
FRM (SLCT MNTH(cntcr_datc) as cntcr_month
FRM works_on) AS m
GRUP 8Y cntcr_month,
188 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Thc rcsult is
eater_meath
z
+
z
Gcncrally, it is possiblc to writc a tablc cxprcssion any placc in a SLCT statcmcnt
whcrc a tablc can appcar. (Thc rcsult ol a tablc cxprcssion is always a tablc or, in a spccial
casc, an cxprcssion.) xamplc 6.72 shows thc usc ol a tablc cxprcssion in a SLCT list.
XAMPL 6.72
US samplc,
SLCT w.job, (SLCT c.cmp_lnamc
FRM cmploycc c VHR c.cmp_no - w.cmp_no) AS namc
FRM works_on w
VHR w.job !N ('Managcr', 'Analyst'),
Thc rcsult is
[eh aame
|a+|.t Ieae.
M+a+er Ieae.
|a+|.t |+a.e|
M+a+er |ertea|
Common 7abIe xpressions
A common tablc cxprcssion (CT) is a namcd tablc cxprcssion that is supportcd by
TransactSQL. Thcrc arc two typcs ol qucrics, which usc CT:
Nonrccursivc qucrics
Rccursivc qucrics
Thc lollowing scctions dcscribc both qucry typcs.
Cha pt er 6 : Quer i es 189
||s se:||cs c|sc 1es:/||es ||e /||| c(e/c|c/, |e:case || ases t| |s ||e scme ac, cs scs-/e:a/s||e cs1
/e:a/s||e ae/|es 1c.
C7s and Nonrecursive Queries
Thc nonrccursivc lorm ol a CT can bc uscd as an altcrnativc to dcrivcd tablcs and
vicws. Gcncrally, a CT is dclincd using thc V!TH statcmcnt and an additional qucry
that rclcrs to thc namc uscd in V!TH (scc xamplc 6.74).
|e || |e,ac/1 |s cm||acas |s ||e /cssc:|-:9| |csace. c c|c|1 cm||a||,, ,ca |c|e |c ase c sem|:c|cs
(, |c |e/m|sc|e ||e s|c|emes| (/e:e1|s ||e || s|c|emes|.
xamplcs 6.73 and 6.74 usc thc AdventureWorks databasc to show how CTs
can bc uscd in nonrccursivc qucrics. xamplc 6.73 uscs thc "convcnicnt" lcaturcs, whilc
xamplc 6.74 solvcs thc samc problcm using a nonrccursivc qucry.
|/ ,ca 1c sc| |c|e ||e 44reatateetks 1c|c|cse cs ,ca/ s,s|em, ,ca :cs 1cas|cc1 || //cm aaa.:c1e(|es
.:cm//:||3|/c1:cm(|es.
XAMPL 6.73
US AdvcnturcVorks,
SLCT Salcsrdcr!
FRM Salcs.SalcsrdcrHcadcr
VHR Totaluc ~ (SLCT A\G(Totaluc)
FRM Salcs.SalcsrdcrHcadcr
VHR YAR(rdcratc) - '2002')
AN Frcight ~ (SLCT A\G(Totaluc)
FRM Salcs.SalcsrdcrHcadcr
VHR YAR(rdcratc) - '2002')/2.5,
Thc qucry in xamplc 6.73 linds total ducs whosc valucs arc grcatcr than thc avcragc
ol all ducs and whosc lrcights arc grcatcr than 40 pcrccnt ol thc avcragc ol all ducs.
190 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Thc main propcrty ol this qucry is that it is spaccconsuming, bccausc an inncr qucry
has to bc writtcn twicc. nc way to shortcn thc syntax ol thc qucry is to crcatc a vicw
containing thc inncr qucry, but that is rathcr complicatcd, bccausc you would havc to
crcatc thc vicw and thcn drop it whcn you arc donc with thc qucry. A bcttcr way is to
writc a CT. xamplc 6.74 shows thc usc ol thc nonrccursivc CT, which shortcns
thc dclinition ol thc qucry in xamplc 6.73.
XAMPL 6.74
US AdvcnturcVorks,
V!TH pricc_calc(ycar_2002) AS
(SLCT A\G(Totaluc)
FRM Salcs.SalcsrdcrHcadcr
VHR YAR(rdcratc) - '2002')
SLCT Salcsrdcr!
FRM Salcs.SalcsrdcrHcadcr
VHR Totaluc ~ (SLCT ycar_2002 FRM pricc_calc)
AN Frcight ~ (SLCT ycar_2002 FRM pricc_calc)/2.5,
Thc syntax lor thc V!TH clausc in nonrccursivc qucrics is
V!TH ctc_namc (column_list) AS
( inncr_qucry)
outcr_qucry
cte_name is thc namc ol thc CT that spccilics a rcsulting tablc. Thc list ol columns
that bclong to thc tablc cxprcssion is writtcn in brackcts. (Thc CT in xamplc 6.74
is callcd price_calc and has onc column, year_2002.) inner_query in thc CT syntax
dclincs thc SLCT statcmcnt, which spccilics thc rcsult sct ol thc corrcsponding
tablc cxprcssion. Altcr that, you can usc thc dclincd tablc cxprcssion in an outcr qucry.
(Thc outcr qucry in xamplc 6.74 uscs thc CT callcd price_calc and its column
year_2002 to simplily thc inncr qucry, which appcars twicc.)
C7s and Recursive Queries
|e mc|e/|c| |s |||s sa|se:||cs |s :cm(|es. |e/e/c/e, s||((|s || cs ||e /|/s| /ec1|s c/ ||e |cc| |s /e:cmmes1e1.
Cha pt er 6 : Quer i es 191
You can usc CTs to implcmcnt rccursion, bccausc CTs can contain rclcrcnccs to
thcmsclvcs. Thc basic syntax lor a CT lor rccursivc qucrics is
V!TH ctc_namc (column_list) AS
(anchor_mcmbcr
UN!N ALL
rccursivc_mcmbcr)
outcr_qucry
cte_name and column_list havc thc samc mcaning as in CTs lor nonrccursivc
qucrics. Thc body ol thc V!TH clausc compriscs two qucrics that arc conncctcd with
thc UN!N ALL opcrator. Thc lirst qucry will bc invokcd only oncc, and it starts to
accumulatc thc rcsult ol thc rccursion. Thc lirst opcrand ol UN!N ALL docs not
rclcrcncc thc CT (scc xamplc 6.75). This qucry is callcd thc anchor query or seed.
Thc sccond qucry contains a rclcrcncc to thc CT and rcprcscnts thc rccursivc
portion ol it. For this rcason it is callcd thc recursi.e member. !n thc lirst invocation ol
thc rccursivc part, thc rclcrcncc to thc CT rcprcscnts thc rcsult ol thc anchor qucry.
Thc rccursivc mcmbcr uscs thc qucry rcsult ol thc lirst invocation. Altcr that, thc
systcm rcpcatcdly invokcs thc rccursivc part. Thc invocation ol thc rccursivc mcmbcr
cnds whcn thc rcsult ol thc prcvious invocation is an cmpty sct.
Thc UN!N ALL opcrator joins thc rows accumulatcd so lar, as wcll as thc
additional rows that arc addcd in thc currcnt invocation. (!nclusion ol UN!N ALL
mcans that no duplicatc rows will bc climinatcd lrom thc rcsult.)
Finally, outer query dclincs a qucry spccilication that uscs thc CT to rctricvc all
invocations ol thc union ol both mcmbcrs.
Thc tablc dclinition in xamplc 6.75 will bc uscd to dcmonstratc thc rccursivc lorm
ol CTs.
XAMPL 6.75
US samplc,
CRAT TA8L airplanc
(containing_asscmbly \ARCHAR(10),
containcd_asscmbly \ARCHAR(10),
quantity_containcd !NT,
unit_cost C!MAL (6,2)),
inscrt into airplanc valucs ( 'Airplanc', 'Fusclagc',1, 10),
inscrt into airplanc valucs ( 'Airplanc', 'Vings', 1, 11),
inscrt into airplanc valucs ( 'Airplanc', 'Tail',1, 12),
inscrt into airplanc valucs ( 'Fusclagc', 'Cockpit', 1, 13),
inscrt into airplanc valucs ( 'Fusclagc', 'Cabin', 1, 14),
inscrt into airplanc valucs ( 'Fusclagc', 'Nosc',1, 15),
192 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
inscrt into airplanc valucs ( 'Cockpit', NULL, 1,13),
inscrt into airplanc valucs ( 'Cabin', NULL, 1, 14),
inscrt into airplanc valucs ( 'Nosc', NULL, 1, 15),
inscrt into airplanc valucs ( 'Vings', NULL,2, 11),
inscrt into airplanc valucs ( 'Tail', NULL, 1, 12),
Thc airplane tablc contains lour columns. Thc column containing_assembly
spccilics an asscmbly, whilc contained_assembly compriscs thc parts (onc by onc) that
build thc corrcsponding asscmbly. (Figurc 61 shows graphically how an airplanc with
its parts could look.)
Supposc that thc airplane tablc contains 11 rows, which arc shown in Tablc 62.
(Thc !NSRT statcmcnts in xamplc 6.75 inscrt thcsc rows in thc airplane tablc.)
xamplc 6.76 shows thc usc ol thc V!TH clausc to dclinc a qucry that calculatcs
thc total costs ol cach asscmbly.
Airplane
Fuselage Wings
Cockpit Nose Cabin
Tail
||qcre 6-1 |/eses|c||cs c/ cs /|/(|cse cs1 ||s |c/|s
||rj|+ae |a.e|+e
||rj|+ae \|a.
||rj|+ae I+|| z
|a.e|+e Cec|j|t 1
|a.e|+e C+||a +
|a.e|+e Ne.e !
Cec|j|t NJ|| 1
C+||a NJ|| +
Ne.e NJ|| !
\|a. NJ|| z
I+|| NJ|| z
Iah|e 6-1 |e tcs|es| c/ ||e /|/(|cse c||e
Cha pt er 6 : Quer i es 193
XAMPL 6.76
US samplc,
V!TH list_ol_parts(asscmbly1, quantity, cost) AS
(SLCT containing_asscmbly, quantity_containcd, unit_cost
FRM airplanc
VHR containcd_asscmbly !S NULL
UN!N ALL
SLCT a.containing_asscmbly, a.quantity_containcd,
CAST(l.quantityl.cost AS C!MAL(6,2))
FRM list_ol_parts l,airplanc a
VHR l.asscmbly1 - a.containcd_asscmbly)
SLCT FRM list_ol_parts,
Thc V!TH clausc dclincs thc CT callcd list_of_parts, which contains thrcc columns:
assembly, quantity, and cost. Thc lirst SLCT statcmcnt in xamplc 6.76 will bc
invokcd only oncc, to accumulatc thc rcsults ol thc lirst stcp in thc rccursion proccss.
Thc SLCT statcmcnt in thc last row ol xamplc 6.76 displays thc lollowing rcsult:
kssemh| 0caat|t Cests
Cec|j|t 1.
C+||a +.
Ne.e .!
\|a. z .
I+|| z.
||rj|+ae z.
||rj|+ae zz.
|a.e|+e .!
||rj|+ae .!
|a.e|+e +.
||rj|+ae +.
|a.e|+e 1.
||rj|+ae 1.
Thc lirst livc rows in thc prcccding output show thc rcsult sct ol thc lirst invocation
ol thc anchor mcmbcr ol thc qucry in xamplc 6.76. All othcr rows arc thc rcsult ol
thc rccursivc mcmbcr (sccond part) ol thc qucry in thc samc cxamplc. Thc rccursivc
194 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
mcmbcr ol thc qucry will bc invokcd twicc: thc lirst timc lor thc lusclagc asscmbly and
thc sccond timc lor thc airplanc itscll.
Thc qucry in xamplc 6.77 will bc uscd to gct thc costs lor cach asscmbly with all
its subparts.
XAMPL 6.77
US samplc,
V!TH list_ol_parts(asscmbly, quantity, cost) AS
(SLCT containing_asscmbly, quantity_containcd, unit_cost
FRM airplanc
VHR containcd_asscmbly !S NULL
UN!N ALL
SLCT a.containing_asscmbly, a.quantity_containcd,
CAST(l.quantityl.cost AS C!MAL(6,2))
FRM list_ol_parts l,airplanc a
VHR l.asscmbly - a.containcd_asscmbly )
SLCT asscmbly, SUM(quantity) parts, SUM(cost) sum_cost
FRM list_ol_parts
GRUP 8Y asscmbly,
Thc output ol thc qucry in xamplc 6.77 is as lollows:
kssemh| |arts !cm_cest
||rj|+ae ! I.
C+||a +.
Cec|j|t 1.
|a.e|+e 1 +z.
Ne.e .!
I+|| z.
\|a. z .
Thcrc arc scvcral rcstrictions lor a CT in a rccursivc qucry:
mcmbcr and onc rccursivc mcmbcr) combincd by thc UN!N ALL opcrator.
Cha pt er 6 : Quer i es 195
typc ol thc corrcsponding column in thc anchor mcmbcr.
thc CT.
mcmbcr: SLCT !ST!NCT, GRUP 8Y, HA\!NG, aggrcgation lunctions,
TP, and subqucrics. (Also, thc only join opcration that is allowcd in thc qucry
7he APPLY Operator
Thc APPLY opcrator is similar to rccursivc qucrics, bccausc it uscs CTs in thc samc
way. This opcrator allows you to invokc a tablcvalucd lunction lor cach row rcturncd
by an outcr tablc cxprcssion ol a qucry. Thc tablcvalucd lunction acts as thc right input,
and thc outcr tablc cxprcssion acts as thc lclt input. Thc right input is cvaluatcd lor
cach row lrom thc lclt input, and thc rows produccd arc combincd lor thc linal output.
Thc list ol columns produccd by thc APPLY opcrator is thc sct ol columns in thc lclt
input lollowcd by thc list ol columns rcturncd by thc right input. (Scc Chaptcr 8 lor thc
dctailcd dcscription ol thc APPLY opcrator.)
ConcIusion
This chaptcr covcrcd all thc lcaturcs ol thc SLCT statcmcnt rcgarding data rctricval
lrom onc or morc tablcs. vcry SLCT statcmcnt that rctricvcs data lrom a tablc
must contain at lcast a SLCT list and thc FRM clausc. Thc FRM clausc
spccilics thc tablc(s) lrom which thc data is rctricvcd. Thc most important optional
clausc is thc VHR clausc, containing onc or morc conditions that can bc combincd
using thc 8oolcan opcrators AN, R, and NT. Hcncc, thc conditions in thc
VHR clausc placc thc rcstriction on thc sclcctcd row.
xercises
.6.1
Gct all rows ol thc works_on tablc.
.6.2
Gct thc cmploycc numbcrs lor all clcrks.
196 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
.6.3
Gct thc cmploycc numbcrs lor cmployccs working on projcct p2 and having cmploycc
numbcrs lowcr than 10000. Solvc this problcm with two dillcrcnt but cquivalcnt
SLCT statcmcnts.
.6.4
Gct thc cmploycc numbcrs lor cmployccs who didn't cntcr thcir projcct in 2007.
.6.5
Gct thc cmploycc numbcrs lor all cmployccs who havc a lcading job (i.c., Analyst or
Managcr) in projcct p1.
.6.6
Gct thc cntcr datcs lor all cmployccs in projcct p2 whosc jobs havc not bccn
dctcrmincd yct.
.6.7
Gct thc cmploycc numbcrs and last namcs ol all cmployccs whosc lirst namcs contain
two lcttcr t's.
.6.8
Gct thc cmploycc numbcrs and lirst namcs ol all cmployccs whosc last namcs havc a
lcttcr o or a as thc sccond charactcr and cnd with thc lcttcrs es.
.6.9
Find thc cmploycc numbcrs ol all cmployccs whosc dcpartmcnts arc locatcd in Scattlc.
.6.10
Find thc last and lirst namcs ol all cmployccs who cntcrcd thcir projccts on 04.01.2007.
.6.11
Group all dcpartmcnts using thcir locations.
.6.12
Vhat is a dillcrcncc bctwccn thc !ST!NCT and GRUP 8Y clauscs:
.6.13
How docs thc GRUP 8Y clausc managc thc NULL valucs: ocs it corrcspond to
thc gcncral trcatmcnt ol thcsc valucs:
Cha pt er 6 : Quer i es 197
.6.14
Vhat is thc dillcrcncc bctwccn CUNT() and CUNT(column):
.6.15
Find thc highcst cmploycc numbcr.
.6.16
Gct thc jobs that arc donc by morc than two cmployccs.
.6.17
Find thc cmploycc numbcrs ol all cmployccs who arc clcrks or work lor dcpartmcnt d3.
.6.18
Vhy is thc lollowing statcmcnt wrong:
SLCT projcct_namc
FRM projcct
VHR projcct_no -
(SLCT projcct_no FRM works_on VHR Job - 'Clcrk')
Vritc thc corrcct syntax lorm lor thc statcmcnt.
.6.19
Vhat is a practical usc ol tcmporary tablcs:
.6.20
Vhat is a dillcrcncc bctwccn global and local tcmporary tablcs:
Vritc all solutions conccrning thc cxcrciscs that usc a join opcration using thc
cxplicit join syntax.
.6.21
For thc project and works_on tablcs, crcatc thc lollowing:
a. Natural join
b. Cartcsian product
.6.22
!l you intcnd to join scvcral tablcs in a qucry (say n tablcs), how many join conditions
arc nccdcd:
198 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
.6.23
Gct thc cmploycc numbcrs and job titlcs ol all cmployccs working on projcct Gcmini.
.6.24
Gct thc lirst and last namcs ol all cmployccs that work lor dcpartmcnts Rcscarch or
Accounting.
.6.25
Gct thc cntcr datcs ol all clcrks that bclong to thc dcpartmcnt d1.
.6.26
Gct thc namcs ol projccts on which two or morc clcrks arc working.
.6.27
Gct thc lirst and last namcs ol thc cmployccs that arc managcrs and that work on
projcct Mcrcury.
.6.28
Gct thc lirst and last namcs ol all cmployccs who cntcrcd thc projcct at thc samc timc
as at lcast onc othcr cmploycc.
.6.29
Gct thc cmploycc numbcrs ol thc cmployccs living in thc samc location and bclonging
to thc samc dcpartmcnt as onc anothcr. (Hint: Usc thc cxtcndcd sample databasc.)
.6.30
Gct thc cmploycc numbcrs ol all cmployccs bclonging to thc Markcting dcpartmcnt.
Find two cquivalcnt solutions using
In 7bis Cbapter
INSR7 Statement
UPDA7 Statement
DL7 Statement
MRC Statement
DU7PU7 CIause
Modlllcatlon ol a
Jablc`s Contcnts
Cbapter 7
Copyright 2008 by The McGraw-Hill Companies. Click here for terms of use.
200 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Cbapter 10
Copyright 2008 by The McGraw-Hill Companies. Click here for terms of use.
258 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
T
his chaptcr dcscribcs indiccs and thcir rolc in optimizing thc rcsponsc timc ol
qucrics. Thc lirst part ol thc chaptcr discusscs how indiccs arc storcd and thc
cxisting lorms ol thcm. Thc main part ol thc chaptcr cxplains thrcc Transact
SQL statcmcnts pcrtaining to indiccs: CRAT !NX, ALTR !NX, and
RP !NX. Altcr that, indcx lragmcntation and its impact on thc pcrlormancc
ol thc systcm will bc cxplaincd. Thc ncxt part ol thc chaptcr givcs you scvcral gcncral
rccommcndations lor how and whcn indiccs should bc crcatcd. At thc cnd ol thc
chaptcr indiccs on computcd columns will bc dcscribcd.
Introduction
atabasc systcms gcncrally usc indiccs to providc last acccss to rclational data. An
indcx is a scparatc physical data structurc that cnablcs qucrics to acccss onc or morc
data rows last. Propcr tuning ol indiccs is thcrclorc a kcy lor qucry pcrlormancc.
An indcx is in many ways analogous to a book indcx. Vhcn you arc looking lor
a topic in a book, you usc its indcx to lind thc pagc(s) whcrc that topic is dcscribcd.
Similarly, whcn you scarch lor a row ol a tablc, atabasc nginc uscs an indcx to lind
its physical location. Howcvcr, thcrc arc two main dillcrcnccs bctwccn a book indcx and
a databasc indcx:
possibility gcncrally docs not cxist il you usc a databasc systcm: thc systcm
componcnt callcd qucry optimizcr dccidcs whcthcr or not to usc an cxisting
indcx. (A uscr can manipulatc thc usc ol indiccs by using indcx hints, but thcir
dcscribcd in Chaptcr 20.)
A particular book's indcx is cditcd togcthcr with thc book and docs not changc
dctcrmincd in thc indcx. 8y contrast, a databasc indcx can changc cach timc thc
corrcsponding data is changcd.
!l a tablc docs not havc an appropriatc indcx, thc databasc systcm uscs thc tablc scan
mcthod to rctricvc rows. Table scan mcans that cach row is rctricvcd and cxamincd in
scqucncc (lrom lirst to last) and rcturncd in thc rcsult sct il thc scarch condition in thc
VHR clausc cvaluatcs to truc. Thcrclorc, all rows arc lctchcd according to thcir physical
mcmory location. This mcthod is lcss cllicicnt than an indcx acccss, as cxplaincd ncxt.
!ndiccs arc storcd in additional data structurcs callcd index pages. (Thc structurc ol
indcx pagcs is vcry similar to thc structurc ol data pagcs, as you will scc in Chaptcr 15.)
For cach indcxcd row thcrc is an index entry, which is storcd in an indcx pagc.
Cha pt er l 0: | ndi c es 259
ach indcx cntry consists ol thc indcx kcy plus a pointcr. For this rcason, cach indcx
cntry is signilicantly shortcr than thc corrcsponding row. Thcrclorc, thc numbcr ol
indcx cntrics pcr (indcx) pagc is signilicantly highcr than thc numbcr ol rows pcr
(data) pagc. This indcx propcrty plays a vcry important rolc, bccausc thc numbcr ol
!/ opcrations rcquircd to travcrsc thc indcx structurc is signilicantly lowcr than
thc numbcr ol !/ opcrations rcquircd to travcrsc thc corrcsponding data pagcs. !n
othcr words, a tablc scan would probably rcsult in many morc !/ opcrations than a
corrcsponding indcx acccss would.
atabasc nginc's indiccs arc constructcd using thc 8
trcc has a trcclikc structurc in which all ol thc bottommost nodcs (lcal
nodcs) arc thc samc numbcr ol lcvcls away lrom thc top (root nodc) ol thc trcc. This
propcrty is maintaincd cvcn whcn ncw data is addcd or dclctcd lrom thc indcxcd column.
Figurc 101 illustratcs thc structurc ol thc 8
trcc consists ol a root nodc, lcal nodcs, and zcro or morc intcrmcdiatc nodcs.
Scarching lor thc data valuc 25348 can bc cxccutcd as lollows: Starting lrom thc
root ol thc 8
trcc, a scarch procccds lor a lowcst kcy valuc grcatcr than or cqual to thc
valuc to bc rctricvcd. Thcrclorc, thc valuc 29346 is rctricvcd lrom thc root nodc, thcn
||qcre 1-1 3
+
-|/ee /c/ ||e em(_sc :c|ams c/ ||e em(|c,ee |c||e
260 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
thc valuc 28559 is lctchcd lrom thc intcrmcdiatc lcvcl, and thc scarchcd valuc, 25348,
is rctricvcd at thc lcal lcvcl. Vith thc hclp ol thc rcspcctivc pointcrs, thc appropriatc
row is rctricvcd. (An altcrnativc, but cquivalcnt, scarch mcthod would bc to scarch lor
smallcr or cqual valucs.)
!ndcx acccss is gcncrally thc prclcrrcd and obviously advantagcous mcthod lor
acccssing tablcs with many rows. Vith indcx acccss, it takcs only a lcw !/ opcrations
to lind any row ol a tablc in a vcry short timc, whcrcas scqucntial acccss rcquircs much
morc timc to lind a row physically storcd at thc cnd ol thc tablc.
3es|1es :cs|es|es| 3
+
-|/ee |s1|:es cs1 |s1|:es cs :cm(a|e1 :c|amss, a||:| a||| |e 1es:/||e1 |s |||s :|c(|e/,
:9| :e/|e/ sa((c/|s c||e/ ||s1s c/ |s1|:es, sa:| cs (c/||||cse1, //|, cs1 /a||-|es| |s1|:es. |c/|||| cse1 |s1|:es c/e
ase1 a||| (c/||||cse1 |c||es cs1 c/e 1es:/||e1 |s t|c(|e/ 1. |s1|:es |s /e|c||cs |c //| c/e es(|c|se1 |s 1e|c|| |s
t|c(|e/ 1?. |a||-|es| |s1|:es c/e ca| c/ ||e s:c(e c/ |||s |cc|.
Thc two cxisting indcx typcs, clustcrcd and nonclustcrcd indiccs, arc dcscribcd ncxt,
altcr which you will lind out how to crcatc an indcx.
CIustered Indices
A clustcrcd indcx dctcrmincs thc physical ordcr ol thc data in a tablc. atabasc nginc
allows thc crcation ol a singlc clustcrcd indcx pcr tablc, bccausc thc rows ol thc tablc
cannot bc physically ordcrcd morc than onc way. Vhcn using a clustcrcd indcx, thc
systcm navigatcs down lrom thc root ol thc 8
trcc. Using this M\, you can obtain inlormation about thc dcgrcc ol
lragmcntation ol rows on data pagcs. You can usc this inlormation to dccidc whcthcr
rcorganization ol thc data is ncccssary.
xamplc 10.3 shows how you can usc thc sys.dm_db_index_physical_stats vicw.
(You nccd to drop all cxisting indiccs on thc works_on tablc bclorc you start thc batch.)
XAMPL 10.3
CLAR Cdb_id !NT,
CLAR Ctab_id !NT,
CLAR Cind_id !NT,
Cha pt er l 0: | ndi c es 267
ST Cdb_id - 8_!('samplc'),
ST Ctab_id - 8JCT_!('cmploycc'),
SLCT avg_lragmcntation_in_pcrccnt, avg_pagc_spacc_uscd_in_pcrccnt
FRM sys.dm_db_indcx_physical_stats
(Cdb_id, Ctab_id, NULL, NULL, NULL)
As you can scc lrom xamplc 10.3, thc sys.dm_db_index_physical_stats vicw has
livc paramctcrs. Thc lirst thrcc spccily thc !s ol thc currcnt databasc, tablc, and indcx,
rcspcctivcly. Thc lorth spccilics thc partition ! (scc Chaptcr 26), and thc last onc
spccilics thc scan lcvcl that is uscd to obtain statistics. (You can always usc NULL to
spccily thc dclault valuc ol thc particular paramctcr.)
This vicw has scvcral columns, ol which avg_fragmentation_in_percent and avg_
page_space_used_in_percent arc thc most important. Thc lormcr spccilics thc avcragc
lragmcntation in pcrccnt, whilc thc lattcr dclincs thc pcrccntagc ol thc uscd spacc.
diting Index Information
Altcr you havc vicwcd thc indcx lragmcntation inlormation, as discusscd in thc prcvious
scction, you can usc thc lollowing systcm lcaturcs to cdit that inlormation and to cdit
othcr indcx inlormation:
sys.indexes catalog vicw
sys.index_columns catalog vicw
sp_helpindex systcm proccdurc
8JCTPRPRTY propcrty lunction
SQL Scrvcr Managcmcnt Studio
sys.dm_db_index_usage_stats M\
sys.dm_db_missing_index_details M\
Thc sys.indexes catalog vicw contains a row lor cach indcx and a row lor cach tablc
without a clustcrcd indcx. Thc most important columns ol this vicw arc object_id,
name, and index_id. object_id is thc namc ol thc databasc objcct to which thc indcx
bclongs, whilc name and index_id arc thc namc and thc ! ol that indcx, rcspcctivcly.
Thc sys.index_columns catalog vicw contains a row pcr column that is part ol an
indcx or a hcap. This inlormation can bc uscd togcthcr with thc inlormation lrom thc
sys.indexes catalog vicw to obtain lurthcr propcrtics ol a spccilic indcx.
268 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
sp_helpindex displays all indiccs on a tablc as wcll as column statistics. Thc syntax ol
this proccdurc is
sp_hclpindcx |Cdb_objcct - | 'namc',
whcrc db_object is thc namc ol a tablc.
Thc 8JCTPRPRTY propcrty lunction has two propcrtics in rclation to
indiccs: sndexed and sndexable. Thc lormcr inlorms you whcthcr a tablc or vicw
has an indcx, whilc thc lattcr spccilics whcthcr a tablc or vicw can bc indcxcd.
To cdit inlormation about an cxisting indcx using SQL Scrvcr Managcmcnt Studio,
choosc thc databasc in thc Databases loldcr and sclcct Tables. xpand thc ndexes
loldcr. Thc list ol all cxisting indiccs lor that tablc is shown. Altcr you doublcclick onc
ol thc indiccs, thc systcm shows you thc ndex Properties dialog box with all propcrtics
ol that indcx. (You can also usc Managcmcnt Studio to crcatc a ncw indcx or drop an
cxisting onc.)
Thc sys.dm_db_index_usage_stats \icw rcturns counts ol dillcrcnt typcs ol indcx
opcrations and thc timc cach typc ol opcration was last pcrlormcd. vcry individual
scck, lookup, or updatc on thc spccilicd indcx by onc qucry cxccution is countcd as a
usc ol that indcx and incrcmcnts thc corrcsponding countcr in this M\. That way you
can gct gcncral inlormation about how oltcn an indcx is uscd i.c. indiccs which arc uscd
morc hcavily than thc othcrs.
Thc sys.dm_db_missing_index_details \icw rcturns dctailcd inlormation about
missing indiccs. Thc most important columns ol this M\ arc index_handle and
object_id. Thc lormcr idcntilics a particular missing indcx, whilc thc lattcr spccilics thc
tablc whcrc thc indcx is missing.
AItering Indices
atabasc nginc is onc ol a lcw databasc systcms that support thc ALTR !NX
statcmcnt. This statcmcnt can bc uscd lor indcx maintcnancc activitics. Thc syntax ol
thc ALTR !NX statcmcnt is vcry similar to thc syntax ol thc CRAT !NX
statcmcnt. !n othcr words, this statcmcnt allows you to changc thc scttings lor thc
lollowing options: ALLV_RV_LCKS, ALLV_PAG_LCKS, !GNR_
UP_KY, and STAT!ST!CS_NRCMPUT.
!n addition to thc prcccding options, thc ALTR !NX statcmcnt supports thrcc
othcr activitics:
Rcbuilding an indcx using thc R8U!L option
Rcorganizing lcal indcx pagcs using thc RRGAN!Z option
isabling an indcx using thc !SA8L option
Cha pt er l 0: | ndi c es 269
Thc lollowing subscctions discuss thcsc options.
|e /||| ||||/ s|c|emes| /e(|c:es c se| c/ :cmmcs1s cs1 s,s|em (/c:e1a/es ||c| acs ase1 |s |e/s|css
(/e||cas |c :9| :e/|e/ 1^^: /c/ |s1es mc|s|escs:e.
RebuiIding an Index
Thcrc arc thrcc ways in which you can rcbuild an indcx:
Usc thc R8U!L option ol thc ALTR !NX statcmcnt
Usc thc RP_X!ST!NG option ol thc CRAT !NX statcmcnt
Usc thc 8CC 8R!NX command
Vith thc R8U!L option, you can rcbuild an indcx. !l you spccily ALL instcad ol
an indcx namc, all indiccs ol thc tablc will bc rcbuilt. (8y allowing indiccs to bc rcbuilt
dynamically, you don't havc to drop and rccrcatc thcm.)
Thc RP_X!ST!NG option ol thc CRAT !NX statcmcnt allows you
to cnhancc pcrlormancc whcn rccrcating a clustcrcd indcx on a tablc that also has a
nonclustcrcd indcx. !t spccilics that thc cxisting clustcrcd or nonclustcrcd indcx should
bc droppcd and thc spccilicd indcx rcbuilt. As you alrcady know, cach nonclustcrcd
indcx in a clustcrcd tablc contains in its lcal nodcs thc corrcsponding valucs ol thc
tablc's clustcrcd indcx. For this rcason, all nonclustcrcd indiccs must bc rcbuilt whcn
a tablc's clustcrcd indcx is droppcd. Using thc RP_X!ST!NG option, you can
prcvcnt thc nonclustcrcd indiccs lrom bcing rcbuilt twicc.
|e ||0|_|/|:|| c(||cs |s mc/e (cae//a| ||cs ||3||||, |e:case || |s mc/e /|es|||e cs1 c//e/s se|e/c| c(||css,
sa:| cs :|cs|s ||e :c|amss ||c| mc|e a( ||e |s1es cs1 :|cs|s c scs:|as|e/e1 |s1es |c c :|as|e/e1 cse.
Thc 8CC 8R!NX command rcbuilds onc or morc indcxcs lor a tablc in
thc spccilicd databasc. (Thc 8R!NX option is a dcprccatcd lcaturc and will bc
rcmovcd in onc ol thc lollowing vcrsions ol SQL Scrvcr.)
Reorganizing Leaf Index Pages
Thc RRGAN!Z option ol thc ALTR !NX statcmcnt spccilics that thc lcal
pagcs ol thc corrcsponding indcx structurc will bc rcorganizcd so that thc physical ordcr
ol thc pagcs matchcs thc lclttoright logical ordcr ol thc lcal nodcs. Thcrclorc, this
270 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
option rcmovcs somc ol thc lragmcntation lrom an indcx, thus improving pcrlormancc.
(RRGAN!Z rcplaccs thc 8CC !NXFRAG command.)
DisabIing an Index
Thc !SA8L option disablcs an cxisting indcx. ach disablcd indcx is unavailablc lor
usc until you cnablc it again. Notc that a disablcd indcx won't bc maintaincd as changcs
to thc corrcsponding data arc madc. For this rcason, indiccs must bc complctcly rcbuilt
il you want to usc thcm again. To cnablc a disablcd indcx, usc thc R8U!L option ol
thc ALTR TA8L statcmcnt.
|/ ,ca 1|sc||e ||e :|as|e/e1 |s1es c/ c |c||e, ||e 1c|c acs| |e c|c||c||e, |e:case c|| 1c|c (ces c/e s|c/e1 |s ||e
|ec/ |e|e| c/ ||e :|as|e/e1 |s1es.
Removing and Renaming Indices
Thc RP !NX statcmcnt rcmovcs onc or morc cxisting indiccs lrom thc currcnt
databasc. Notc that rcmoving thc clustcrcd indcx ol a tablc can bc a vcry rcsourcc
intcnsivc opcration, bccausc all nonclustcrcd indiccs will havc to bc rcbuilt. (All thc
nonclustcrcd indiccs usc thc indcx kcy ol thc clustcrcd indcx as a pointcr in thcir lcal
indcx pagcs.) xamplc 10.4 shows how thc i_empno indcx can bc droppcd.
XAMPL 10.4
Rcmovc thc indcx crcatcd in xamplc 10.1:
US samplc,
RP !NX i_cmpno N cmploycc,
Thc RP !NX statcmcnt has an additional option, M\ T, which is
analogous to thc N option ol CRAT !NX. !n othcr words, you can usc this
option to spccily a location to which to movc thc data rows that arc currcntly in thc lcal
pagcs ol thc clustcrcd indcx. Thc data is movcd to thc ncw location in thc lorm ol a
hcap. You can spccily cithcr a dclault or namcd lilc group as thc ncw location.
|e ||0| ||||/ s|c|emes| :cssc| |e ase1 |c /emc|e |s1|:es ||c| c/e |m(||:|||, ese/c|e1 |, ||e s,s|em /c/
|s|e/||, :css|/c|s|s, sa:| cs |||//| || c/ |||9||. c /emc|e sa:| |s1|:es, ,ca mas| /|/s| 1/c( ||e :css|/c|s|.
Thc sp_rename systcm proccdurc, which is discusscd in Chaptcr 5, can bc uscd to
rcnamc indiccs.
Cha pt er l 0: | ndi c es 271
CuideIines for Creating and Using Indices
Although atabasc nginc docs not havc any practical limitations conccrning thc
numbcr ol indiccs, it is advisablc to limit thcm, lor a couplc ol rcasons. First, cach indcx
uscs a ccrtain amount ol disk spacc, so it is possiblc that thc total numbcr ol indcx
pagcs could cxcccd thc numbcr ol data pagcs within a databasc. Sccond, in contrast to
thc bcnclits ol using an indcx lor rctricvals, inscrts and updatcs havc a dircct impact
on thc maintcnancc ol thc indcx. Thc morc indiccs on thc tablcs, thc morc indcx
rcorganizations that arc ncccssary. Thc rulc ol thumb is to choosc indiccs wiscly lor
lrcqucnt qucrics and cvaluatc indcx usagc altcrwards.
This scction givcs somc rccommcndations lor crcating and using indiccs.
|e /c||ca|s /e:cmmes1c||css c/e ese/c| /a|es c/ ||am|. |e, a|||mc|e|, 1e(es1 cs |ca ,ca/ 1c|c|cse a|||
|e ase1 |s (/c1a:||cs cs1 a||:| ae/|es c/e ase1 mcs| //eaes||,. /s |s1es cs c :c|ams ||c| |s se|e/ ase1 a|||
|e :cas|e/(/c1a:|||e.
Indices and Conditions in tbe WHR CIause
!l thc VHR clausc in a SLCT statcmcnt contains a scarch condition with
a singlc column, you should crcatc an indcx on this column. Thc usc ol an indcx is
cspccially rccommcndcd il thc sclcctivity ol thc condition is high. Thc selecti.ity ol a
condition is dclincd as thc ratio ol thc numbcr ol rows satislying thc condition to thc
total numbcr ol rows in thc tablc. (High sclcctivity corrcsponds to a small ratio.) Thc
most succcsslul proccssing ol a rctricval with thc indcxcd column will bc achicvcd il thc
sclcctivity ol a condition is 5 pcrccnt or lcss.
Thc column should not bc indcxcd il thc sclcctivity ol thc condition is constantly
80 pcrccnt or morc. !n such a casc, additional !/ opcrations will bc nccdcd lor thc
cxisting indcx pagcs, which would climinatc any timc savings gaincd by indcx acccss. !n
this particular casc, a tablc scan would bc lastcr, and thc qucry optimizcr would usually
choosc to usc a tablc scan, rcndcring thc indcx usclcss.
!l a scarch condition in a lrcqucntly uscd qucry contains onc or morc AN
opcrators, it is bcst to crcatc a compositc indcx that includcs all thc columns ol thc tablc
spccilicd in thc VHR clausc ol thc SLCT statcmcnt. xamplc 10.5 shows thc
crcation ol a compositc indcx that includcs all thc columns spccilicd in thc VHR
clausc ol thc SLCT statcmcnt.
272 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
XAMPL 10.5
US samplc,
CRAT !NX i_works N works_on(cmp_no, cntcr_datc),
SLCT cmp_no, projcct_no, cntcr_datc
FRM works_on
VHR cmp_no - 29346 AN cntcr_datc-'1.4.2006',
Thc AN opcrator in this qucry contains two conditions. As such, both ol thc columns
appcaring in cach condition should bc indcxcd using a compositc nonclustcrcd indcx.
Indices and 1oin Dperator
!n thc casc ol a join opcration, it is rccommcndcd that you indcx cach join column. Join
columns oltcn rcprcscnt thc primary kcy ol onc tablc and thc corrcsponding lorcign
kcy ol thc othcr or thc samc tablc. !l you spccily thc PR!MARY KY and FR!GN
KY intcgrity constraints lor thc corrcsponding join columns, only a non clustcrcd
indcx lor thc column with thc lorcign kcy should bc crcatcd, bccausc thc systcm will
implicitly crcatc thc clustcrcd indcx lor thc PR!MARY KY column.
xamplc 10.6 shows thc crcation ol indiccs, which should bc uscd il you havc a
qucry with a join opcration and an additional liltcr.
XAMPL 10.6
US samplc,
SLCT cmp_lnamc, cmp_lnamc
FRM cmploycc, works_on
VHR cmploycc.cmp_no - works_on.cmp_no
AN cntcr_datc - '10.15.2007',
For xamplc 10.6, thc crcation ol two scparatc indiccs lor thc emp_no column in
both thc employee and works_on tablcs is rccommcndcd. Also, an additional indcx
should bc crcatcd lor thc enter_date column.
Covering Index
As you alrcady know, signilicant pcrlormancc gains can bc achicvcd whcn all columns
in thc qucry arc includcd in thc indcx. xamplc 10.7 shows a covcring indcx.
Cha pt er l 0: | ndi c es 273
XAMPL 10.7
US AdvcnturcVorks,
G
RP !NX Pcrson.Addrcss.!X_Addrcss_StatcProvincc!,
G
CRAT !NX i_addrcss_zip
N Pcrson.Addrcss (PostalCodc)
!NCLU (City, StatcProvincc!),
G
SLCT city, statcprovincc!
FRM Pcrson.Addrcss
VHR PostalCodc - 84407,
xamplc 10.7 lirst drops thc X_Address_StateProvinceD indcx ol thc Address
tablc. !n thc sccond stcp, it crcatcs thc ncw indcx, which additionally includcs two othcr
columns, on thc PostalCode column. Finally, thc SLCT statcmcnt at thc cnd ol thc
cxamplc shows a qucry covcrcd by thc indcx. For this qucry, thc systcm docs not havc
to scarch lor data in data pagcs, bccausc thc optimizcr can lind all thc column valucs in
thc lcal pagcs ol thc nonclustcrcd indcx.
|e ase c/ :c|e/|s |s1|:es |s /e:cmmes1e1, |e:case |s1es (ces ese/c||, :cs|c|s mcs, mc/e es|/|es ||cs ||e
:c//es(cs1|s 1c|c (ces :cs|c|s. /|sc, |c ase |||s me||c1, ||e /|||e/e1 :c|amss mas| |e ||e /|/s| |e, :c|amss |s
||e |s1es|
Indices on Computed CoIumns
atabasc nginc allows you to crcatc thc lollowing spccial typcs ol indiccs:
!ndiccs on computcd columns
!ndiccs on vicws
This chaptcr discusscs computcd columns, indcxcd vicws arc cxplaincd in thc ncxt
chaptcr.
A computed column is a column ol a tablc that is uscd to storc thc rcsult ol a
computation ol thc tablc's data. Such a column can bc cithcr virtual or pcrsistcnt. Thc
lollowing subscctions dcscribc thcsc two lorms ol computcd columns.
274 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
VirtuaI Computed CoIumns
A computcd column without a corrcsponding clustcrcd indcx is logicalthat is, it
is not physically storcd on thc hard disk. Hcncc, it is rccomputcd cach timc a row is
acccsscd.
xamplc 10.8 dcmonstratcs thc usc ol virtual computcd columns.
XAMPL 10.8
US samplc,
CRAT TA8L ordcrs
(ordcrid !NT NT NULL,
pricc MNY NT NULL,
quantity !NT NT NULL,
ordcrdatc ATT!M NT NULL,
total AS pricc quantity,
shippcddatc AS ATA (AY, 7, ordcrdatc)),
Thc orders tablc in xamplc 10.8 has two computcd columns: total and shippeddate.
Thc total column is computcd using two othcr columns, price and quantity, whilc thc
shippeddate column is computcd using thc datc lunction ATA and thc column
orderdate.
Persistent Computed CoIumns
atabasc nginc allows you to build indiccs on dctcrministic computcd columns,
whcrc thc undcrlying columns havc prccisc data typcs. (A computcd column is callcd
dctcrministic il thc samc valucs will always bc rcturncd lor thc samc tablc data.)
An indcxcd computcd column can bc crcatcd only il thc lollowing options ol thc
ST statcmcnt arc sct to N. (Thcsc options guarantcc thc dctcrminism ol thc
column.)
QUT_!NT!F!R
CNCAT_NULL_Y!LS_NULL
ANS!_NULLS
ANS!_PA!NG
ANS!_VARN!NGS
Also, thc NUMR!C_RUNA8RT option must bc sct to FF.
Cha pt er l 0: | ndi c es 275
tc|amss ase1 /c/ |s1ese1 ||eas mas| /a|/||| ||e scme :cs1|||css cs |s1esc||e :cm(a|e1 :c|amss. |e se:||cs cs
|s1ese1 ||eas |s ||e ses| :|c(|e/ s|cas |ca ,ca :cs :|e:| a|e||e/ ||e (/e:e1|s c(||css c/e c((/c(/|c|e|, se|.
!l you crcatc a clustcrcd indcx on a computcd column, thc valucs ol thc column will
physically cxist in thc corrcsponding tablc rows, bccausc lcal pagcs ol thc clustcrcd
indcx contain data rows (scc thc "Clustcrcd !ndiccs" scction carlicr in this chaptcr).
xamplc 10.9 shows thc crcation ol a clustcrcd indcx lor thc computcd column total
in xamplc 10.8.
XAMPL 10.9
CRAT CLUSTR !NX i1 N ordcrs (total),
Altcr thc cxccution ol thc CRAT !NX statcmcnt in xamplc 10.9, thc computcd
column total will physically cxist. This mcans that all updatcs to thc undcrlying columns
that build thc computcd column will causc thc modilication ol thc computcd column itscll.
PRSIS7D Option
Sincc SQL Scrvcr 2005, it is possiblc to mark a computcd column cxplicitly as
pcrsistcnt, using thc PRS!ST option. This option allows you to spccily that thc
computcd column will physically cxist in thc corrcsponding tablc rows, cvcn il thc
corrcsponding clustcrcd indcx isn't crcatcd. This lcaturc is ncccssary lor computcd
columns built upon approximatc data typcs (FLAT and RAL). (As you alrcady
know, you can crcatc an indcx lor a computcd column only il thc undcrlying columns
havc a prccisc data typc.)
ConcIusion
!ndiccs arc uscd to acccss data morc cllicicntly. Thcy can allcct not only SLCT
statcmcnts but also pcrlormancc ol !NSRT, UPAT, and LT statcmcnts. An
indcx can bc clustcrcd or nonclustcrcd, uniquc or nonuniquc, and singlc or compositc.
A clustcrcd indcx physically sorts thc rows ol thc tablc in thc ordcr ol thc spccilicd
column(s). A uniquc indcx spccilics that cach valuc can appcar only oncc in that
column ol thc tablc. A compositc indcx is composcd ol morc than onc column.
A grcat lcaturc in rclation to indiccs is atabasc nginc Tuning Advisor (TA),
which will, among othcr things, analyzc a samplc ol your actual workload (supplicd
276 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
via cithcr a script lilc lrom you or a capturcd tracc lilc lrom SQL Scrvcr Prolilcr) and
rccommcnd indiccs lor you to add or dclctc bascd on that workload. Usc ol TA is
highly rccommcndcd. For morc inlormation on SQL Scrvcr Prolilcr and TA, scc
Chaptcr 21.
Thc ncxt chaptcr discusscs thc notion ol a vicw.
xercises
.10.1
Crcatc a nonclustcrcd indcx lor thc enter_date column ol thc works_on tablc. Sixty
pcrccnt ol cach indcx lcal pagc should bc lillcd.
.10.2
Crcatc a uniquc compositc indcx lor thc l_name and f_name columns ol thc employee
tablc. !s thcrc any dillcrcncc il you changc thc ordcr ol thc columns in thc compositc
indcx:
.10.3
How can you drop thc indcx that is implicitly crcatcd lor thc primary kcy ol a tablc:
.10.4
iscuss thc bcnclits and disadvantagcs ol an indcx.
!n thc lollowing lour cxcrciscs, crcatc indiccs that will improvc pcrlormancc ol thc
qucrics. (Assumc that all tablcs ol thc sample databasc that arc uscd in thc lollowing
cxcrciscs havc a vcry largc numbcr ol rows.)
.10.5
SLCT cmp_no, cmp_lnamc, cmp_lnamc
FRM cmploycc
VHR cmp_lnamc - 'Smith'
.10.6
SLCT cmp_no, cmp_lnamc, cmp_lnamc
FRM cmploycc
VHR cmp_lnamc - 'Hanscl'
AN cmp_lnamc - 'lkc'
Cha pt er l 0: | ndi c es 277
.10.7
SLCT job
FRM works_on, cmploycc
VHR cmploycc.cmp_no - works_on.cmp_no
.10.8
SLCT cmp_lnamc, cmp_lnamc
FRM cmploycc, dcpartmcnt
VHR cmploycc.dcpt_no - dcpartmcnt.dcpt_no
AN dcpt_namc - 'Rcscarch'
This page intentionally left blank
In 7bis Cbapter
DDL Statements and Views
DML Statements and Views
Indexed Views
Cbapter 11
Copyright 2008 by The McGraw-Hill Companies. Click here for terms of use.
280 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
T
his chaptcr is dcdicatcd cxclusivcly to thc databasc objcct callcd a .ie.. Thc
structurc ol this chaptcr corrcsponds to thc structurc ol Chaptcrs 5 to 7, in
which thc L and ML statcmcnts lor basc tablcs wcrc dcscribcd. Thc lirst
scction ol this chaptcr covcrs thc L statcmcnts conccrning vicws: CRAT \!V,
ALTR \!V, and RP \!V. Thc sccond part ol thc chaptcr dcscribcs thc ML
statcmcnts SLCT, !NSRT, UPAT, and LT with vicws. Thc SLCT
statcmcnt will bc lookcd at scparatcly lrom thc othcr thrcc statcmcnts. !n contrast to
basc tablcs, vicws cannot bc uscd lor modilication opcrations without ccrtain limitations.
Thcsc limitations arc dcscribcd at thc cnd ol cach corrcsponding scction.
Thc altcrnativc lorm ol a vicw, callcd an indcxcd vicw, is dcscribcd in thc last major
scction ol this chaptcr. This typc ol indcx matcrializcs thc corrcsponding qucry and allows
you to achicvc signilicant pcrlormancc gains in rclation to qucrics with aggrcgatcd data.
DDL Statements and Views
!n thc prcvious chaptcrs, basc tablcs wcrc uscd to dcscribc L and ML statcmcnts.
A basc tablc contains data storcd on thc disk. 8y contrast, vicws, by dclault, do not cxist
physicallythat is, thcir contcnt is not storcd on thc disk. (This is not truc lor socallcd
indcxcd vicws, which arc discusscd latcr in this chaptcr.) \icws arc databasc objccts that
arc always dcrivcd lrom onc or morc basc tablcs (or vicws) using mctadata inlormation.
This inlormation (including thc namc ol thc vicw and thc way thc rows lrom thc basc
tablcs arc to bc rctricvcd) is thc only inlormation conccrning vicws that is physically
storcd. Thus, vicws arc also callcd .irtual tables.
Creating a View
A vicw is crcatcd using thc CRAT \!V statcmcnt. Thc gcncral lorm ol this
statcmcnt is
CRAT \!V vicw_namc |(column_list)|
|V!TH [NCRYPT!N ] SCHMA8!N!NG ] \!V_MTAATA]|
AS sclcct_statcmcnt
|V!TH CHCK PT!N|
|e t||/| l|| s|c|emes| mas| |e ||e cs|, s|c|emes| |s c |c|:|. (||s mecss ||c| ,ca |c|e |c ase ||e 0
s|c|emes| |c se(c/c|e |||s s|c|emes| //cm c||e/ s|c|emes|s |s c s|c|emes| /ca(.
Cha pt er l l: vi ews 281
view_name is thc namc ol thc dclincd vicw. column_list is thc list ol namcs to bc
uscd lor columns in a vicw. !l this optional spccilication is omittcd, column namcs ol
thc undcrlying tablcs arc uscd. select_statement spccilics thc SLCT statcmcnt
that rctricvcs rows and columns lrom onc or morc tablcs (or vicws). Thc V!TH
NCRYPT!N option cncrypts thc SLCT statcmcnt, thus cnhancing thc sccurity
ol thc databasc systcm.
Thc SCHMA8!N!NG clausc binds thc vicw to thc schcma ol thc undcrlying
tablc. Vhcn SCHMA8!N!NG is spccilicd, databasc objccts rclcrcnccd in thc
SLCT statcmcnt must includc thc twopart namcs in thc lorm owner.db_object,
whcrc db_object may bc a tablc, a vicw, or a uscrdclincd lunction.
Any attcmpt to modily thc structurc ol vicws or tablcs that arc rclcrcnccd in
a vicw crcatcd with this clausc lails. You havc to drop thc vicw or changc it so that it
no longcr has thc SCHMA8!N!NG clausc il you want to apply thc ALTR or
RP statcmcnt to thc rclcrcnccd objccts. (Thc V!TH CHCK PT!N clausc
is discusscd in dctail latcr in this chaptcr in thc scction "!NSRT Statcmcnt and
a \icw.")
Vhcn a vicw is crcatcd with thc \!V_MTAATA option, all ol its columns
(cxccpt columns with thc T!MSTAMP data typc) can bc updatcd il thc vicw has
!NSRT or UPAT !NSTA F triggcrs. (Triggcrs arc dcscribcd in Chaptcr 14.)
|e :|||t s|c|emes| |s c ||ea :cssc| |s:|a1e ||e 0|||| 3, ||0, c/ t0/||| :|cases. /11|||csc||,,
c |em(c/c/, |c||e :cssc| |e /e/e/es:e1 |s ||e ae/,.
\icws can bc uscd lor dillcrcnt purposcs:
can bc uscd lor controlling acccss to a particular part ol onc or morc tablcs (scc
Chaptcr 12).
To hidc thc dctails ol complicatcd qucrics. !l databasc applications nccd qucrics
that involvc complicatcd join opcrations, thc crcation ol corrcsponding vicws can
simplily thc usc ol such qucrics.
To rcstrict inscrtcd and updatcd valucs to ccrtain rangcs.
xamplc 11.1 shows thc crcation ol a vicw.
282 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
XAMPL 11.1
US samplc,
G
CRAT \!V v_clcrk
AS SLCT cmp_no, projcct_no, cntcr_datc
FRM works_on
VHR job - 'Clcrk',
Thc qucry in xamplc 11.1 rctricvcs thc rows ol thc works_on tablc, lor which thc
condition job - 'Clcrk' cvaluatcs to truc. Thc v_clerk vicw is dclincd as thc rows and
columns rcturncd by this qucry. Tablc 111 shows thc works_on tablc with thc rows
that bclong to thc v_clerk vicw boldcd.
xamplc 11.1 spccilics thc sclcction ol rowsthat is, it crcatcs a horizontal subsct lrom
thc basc tablc works_on. !t is also possiblc to crcatc a vicw that limits thc columns as wcll
as thc rows to bc includcd in thc vicw. xamplc 11.2 shows thc crcation ol such a vicw.
XAMPL 11.2
US samplc,
G
CRAT \!V v_without_budgct
AS SLCT projcct_no, projcct_namc
FRM projcct,
emp_ae pre[ect_ae [eh eater_6ate
z j |a+|.t z.. ..
z j1 M+a+er z.. ..
1148 p1 C|erk 1I.1.1 ::
1 jz NJ|| zI.. ..
z1+ jz NJ|| z.z.! ..
z! j1 |a+|.t zI..! ..
1 j M+a+er zI.+.! ..
z!! j NJ|| zI... ..
189 p1 C|erk 18.1.1 ::
911 p1 C|erk 16.11.1 ::
19146 p1 C|erk 1I.1.4 ::
Iah|e 1-1 |e 3cse c||e ac/|s_cs
Cha pt er l l: vi ews 283
Thc v_without_budget vicw in xamplc 11.2 contains all columns ol thc project
tablc cxccpt thc budget column.
As alrcady statcd, spccilying column namcs with a vicw in thc gcncral lormat ol thc
CRAT \!V statcmcnt is optional. n thc othcr hand, thcrc arc also two cascs in
which thc cxplicit spccilication ol column namcs is rcquircd:
!l a column ol thc vicw is dcrivcd lrom an cxprcssion or an aggrcgatc lunction
!l two or morc columns ol thc vicw havc thc samc namc in thc undcrlying tablcs
xamplc 11.3 shows thc cxplicit spccilication ol column namcs in rclation to a vicw.
XAMPL 11.3
US samplc,
G
CRAT \!V v_count(projcct_no, count_projcct)
AS SLCT projcct_no, CUNT()
FRM works_on
GRUP 8Y projcct_no,
Thc column namcs ol thc v_count vicw in xamplc 11.3 must bc cxplicitly spccilicd
bccausc thc SLCT statcmcnt contains thc aggrcgatc lunction CUNT(), and all
columns in a vicw must bc namcd.
You can avoid thc cxplicit spccilication ol thc column list in thc CRAT \!V
statcmcnt il you usc column hcadcrs, as in xamplc 11.4.
XAMPL 11.4
US samplc,
G
CRAT \!V v_count1
AS SLCT projcct_no, CUNT() count_projcct
FRM works_on
GRUP 8Y projcct_no,
A vicw can bc dcrivcd lrom anothcr cxisting vicw, as shown in xamplc 11.5.
XAMPL 11.5
US samplc,
G
CRAT \!V v_projcct_p2
284 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
AS SLCT cmp_no
FRM v_clcrk
VHR projcct_no -'p2',
Thc v_project_p2 vicw in xamplc 11.5 is dcrivcd lrom thc v_clerk vicw
(scc xamplc 11.1). vcry qucry using thc v_project_p2 vicw is convcrtcd into thc
cquivalcnt qucry on thc undcrlying basc tablc works_on.
You can also crcatc a vicw using bjcct xplorcr ol SQL Scrvcr Managcmcnt
Studio. Sclcct thc databasc undcr which you want to crcatc thc vicw, rightclick Views,
and choosc New View. Thc corrcsponding cditor appcars. Using thc cditor, you can do
thc lollowing:
Sclcct undcrlying tablcs and columns lrom thcsc tablcs lor thc vicw
qucry
AItering and Removing Views
Thc TransactSQL languagc supports thc nonstandard ALTR \!V statcmcnt,
which is uscd to modily thc dclinition ol thc vicw qucry. Thc syntax ol ALTR \!V
is analogous to that ol thc CRAT \!V statcmcnt.
You can usc thc ALTR \!V statcmcnt to avoid rcassigning cxisting privilcgcs lor
thc vicw. Also, altcring an cxisting vicw using this statcmcnt docs not allcct databasc
objccts (storcd proccdurcs, usually) that dcpcnd upon thc vicw. thcrwisc, il you usc
thc RP \!V and CRAT \!V statcmcnts to rcmovc and rccrcatc a vicw,
any databasc objcct that uscs thc vicw will not work propcrly, at lcast in thc timc pcriod
bctwccn rcmoving and rccrcating thc vicw.
xamplc 11.6 shows thc usc ol thc ALTR \!V statcmcnt.
XAMPL 11.6
US samplc,
G
ALTR \!V v_without_budgct
AS SLCT projcct_no, projcct_namc
FRM projcct
VHR projcct_no ~- 'p3',
Thc ALTR \!V statcmcnt in xamplc 11.6 cxtcnds thc SLCT statcmcnt
ol thc v_without_budget vicw (scc xamplc 11.2) with thc ncw condition in thc
VHR clausc.
Cha pt er l l: vi ews 285
|e /||| l|| s|c|emes| :cs c|sc |e c((||e1 |c |s1ese1 ||eas. ||s s|c|emes| /emc|es c|| |s1|:es ||c| es|s| /c/
sa:| c ||ea.
Thc RP \!V statcmcnt rcmovcs thc dclinition ol thc spccilicd vicw lrom thc
systcm tablcs. xamplc 11.7 shows thc usc ol thc RP \!V statcmcnt.
XAMPL 11.7
US samplc,
G
RP \!V v_count,
!l thc RP \!V statcmcnt rcmovcs a vicw, all othcr vicws dcrivcd lrom it will
bc droppcd, too, as dcmonstratcd in xamplc 11.8.
XAMPL 11.8
US samplc,
G
RP \!V v_clcrk,
Thc RP \!V statcmcnt in xamplc 11.8 also implicitly rcmovcs thc v_project_
p2 vicw (scc xamplc 11.5). For instancc, il you qucry thc v_project_p2 vicw, you will gct
thc crror: "!nvalid objcct namc: 'v_clcrk'."
/ ||ea |s sc| ca|cmc||:c||, 1/c((e1 |/ ||e as1e/|,|s |c||e |s /emc|e1. ||s mecss ||c| cs, ||ea //cm ||e
/emc|e1 |c||e mas| |e es:|as||e|, /emc|e1 as|s ||e ||0| l|| s|c|emes|. 0s ||e c||e/ |cs1, |/ c |c||e a|||
||e scme |c|:c| s|/a:|a/e cs ||e /emc|e1 cse |s sa|seaes||, :/ec|e1, ||e ||ea :cs |e ase1 cc|s.
diting Information Concerning Views
sys.objects is thc most important catalog vicw conccrning vicws. As you alrcady know,
this catalog vicw contains inlormation in rclation to all objccts ol thc currcnt databasc.
All rows ol this vicw that havc thc valuc V lor thc type column arc vicws.
Anothcr catalog vicw callcd sys.views displays additional inlormation about cxisting
vicws. Thc most important column ol this vicw is with_check_option, which instructs
you whcthcr or not V!TH CHCK PT!N is spccilicd.
286 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Using thc systcm proccdurc sp_helptext, you can display thc qucry bclonging to a
particular vicw.
DML Statements and Views
\icws arc rctricvcd and modilicd with thc samc TransactSQL statcmcnts that arc uscd
to rctricvc and modily basc tablcs. Thc lollowing subscctions discuss all lour ML
statcmcnts in rclation to vicws.
View RetrievaI
A vicw is uscd cxactly likc any basc tablc ol a databasc. You can think ol sclccting
lrom a vicw as il thc statcmcnt wcrc translormcd into an cquivalcnt opcration on thc
undcrlying basc tablc(s). xamplc 11.9 shows this.
XAMPL 11.9
US samplc,
G
CRAT \!V v_d2
AS SLCT cmp_no, cmp_lnamc
FRM cmploycc
VHR dcpt_no -'d2',
G
SLCT cmp_lnamc
FRM v_d2
VHR cmp_lnamc L!K 'J',
Thc rcsult is
emp_|aame
I+me.
Thc SLCT statcmcnt in xamplc 11.9 is translormcd into thc lollowing
cquivalcnt lorm, using thc undcrlying tablc ol thc v_d2 vicw:
SLCT cmp_lnamc
FRM cmploycc
VHR cmp_lnamc L!K 'J'
AN dcpt_no -'d2',
Cha pt er l l: vi ews 287
Thc ncxt thrcc scctions dcscribc thc usc ol vicws with thc othcr thrcc ML
statcmcnts: !NSRT, UPAT, and LT. ata modilication with thcsc
statcmcnts is trcatcd in a manncr similar to a rctricval. Thc only dillcrcncc is that
thcrc arc somc rcstrictions on a vicw uscd lor inscrtion, modilication, and dclction ol
data lrom thc tablc that it dcpcnds on.
INSR7 Statement and a View
A vicw can bc uscd with thc !NSRT statcmcnt as il it wcrc a basc tablc. Vhcn a vicw
is uscd to inscrt rows, thc rows arc actually inscrtcd into thc undcrlying basc tablc.
XAMPL 11.10
US samplc,
G
CRAT \!V v_dcpt
AS SLCT dcpt_no, dcpt_namc
FRM dcpartmcnt,
G
!NSRT !NT v_dcpt
\ALUS('d4', 'cvclopmcnt'),
Thc v_dept vicw, which is crcatcd in xamplc 11.10, contains thc lirst two columns
ol thc department tablc. Thc subscqucnt !NSRT statcmcnt inscrts thc row into thc
undcrlying tablc using thc valucs 'd4' and 'cvclopmcnt'. Thc location column, which
is not rclcrcnccd by thc v_dept vicw, is assigncd a NULL valuc.
Using a vicw, it is gcncrally possiblc to inscrt a row that docs not satisly thc conditions
ol thc vicw qucry's VHR clausc. Thc option V!TH CHCK PT!N is uscd
to rcstrict thc inscrtion ol only such rows that satisly thc conditions ol thc qucry. !l this
option is uscd, atabasc nginc tcsts cvcry inscrtcd row to cnsurc that thc conditions
in thc VHR clausc arc cvaluatcd to truc. !l this option is omittcd, thcrc is no chcck
ol conditions in thc VHR clausc, and thcrclorc cvcry row is inscrtcd into thc
undcrlying tablc. This could lcad to thc conlusing situation ol a row bcing inscrtcd using
a vicw but subscqucntly not bcing rcturncd by a SLCT statcmcnt against that vicw,
bccausc thc VHR clausc is cnlorccd lor thc SLCT. V!TH CHCK PT!N
is also applicd to thc UPAT statcmcnt.
xamplcs 11.11 and 11.12 show thc dillcrcncc ol applying and not applying V!TH
CHCK PT!N, rcspcctivcly.
288 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
XAMPL 11.11
US samplc,
G
CRAT \!V v_2006_chcck
AS SLCT cmp_no, projcct_no, cntcr_datc
FRM works_on
VHR cntcr_datc 8TVN '01.01.2006' AN '12.31.2006'
V!TH CHCK PT!N,
G
!NSRT !NT v_2006_chcck
\ALUS (22334, 'p2', '1.15.2007'),
!n xamplc 11.11, thc systcm tcsts whcthcr thc inscrtcd valuc ol thc enter_date
column cvaluatcs to truc lor thc condition in thc VHR clausc ol thc SLCT
statcmcnt. Thc attcmptcd inscrt lails bccausc thc condition is not mct.
XAMPL 11.12
US samplc,
G
CRAT \!V v_2006_nochcck
AS SLCT cmp_no, projcct_no, cntcr_datc
FRM works_on
VHR cntcr_datc 8TVN '01.01.2006' AN '12.31.2006',
G
!NSRT !NT v_2006_nochcck
\ALUS (22334, 'p2', '1.15.2007'),
SLCT
FRM v_2006_nochcck,
Thc rcsult is
emp_ae pre[ect_ae eater_6ate
z j z--
z1+ jz z-z-!
1 j1 z--!
Cha pt er l l: vi ews 289
8ccausc xamplc 11.12 docs not usc V!TH CHCK PT!N, thc !NSRT
statcmcnt is cxccutcd and thc row is inscrtcd into thc undcrlying works_on tablc.
Noticc that thc subscqucnt SLCT statcmcnt docs not display thc inscrtcd row
bccausc it cannot bc rctricvcd using thc v_2006_nocheck vicw.
Thc inscrtion ol rows into thc undcrlying tablcs is not possiblc il thc corrcsponding
vicw contains any ol thc lollowing lcaturcs:
column list includcs columns lrom morc than onc tablc
A column ol thc vicw is dcrivcd lrom an aggrcgatc lunction
!ST!NCT option
A column ol thc vicw is dcrivcd lrom a constant or an cxprcssion
xamplc 11.13 shows a vicw that cannot bc uscd to inscrt rows in thc undcrlying
basc tablc.
XAMPL 11.13
US samplc,
G
CRAT \!V v_sum(sum_ol_budgct)
AS SLCT SUM(budgct)
FRM projcct,
G
SLCT
FRM v_sum,
xamplc 11.13 crcatcs thc v_sum vicw, which contains an aggrcgatc lunction in
its SLCT statcmcnt. 8ccausc thc vicw in thc cxamplc rcprcscnts thc rcsult ol an
aggrcgation ol many rows (and not a singlc row ol thc project tablc), it docs not makc
scnsc to try to inscrt a row into thc undcrlying tablc using this vicw.
UPDA7 Statement and a View
A vicw can bc uscd with thc UPAT statcmcnt as il it wcrc a basc tablc. Vhcn
a vicw is uscd to modily rows, thc contcnt ol thc undcrlying basc tablc is actually
modilicd.
xamplc 11.14 crcatcs a vicw that is thcn uscd to modily thc works_on tablc.
290 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
XAMPL 11.14
US samplc,
G
CRAT \!V v_p1
AS SLCT cmp_no, job
FRM works_on
VHR projcct_no - 'p1',
G
UPAT v_p1
ST job - NULL
VHR job - 'Managcr',
You can think ol updating thc vicw in xamplc 11.14 as il thc UPAT statcmcnt
wcrc translormcd into thc lollowing cquivalcnt statcmcnt:
UPAT works_on
ST job - NULL
VHR job - 'Managcr'
AN projcct_no - 'p1'
V!TH CHCK PT!N has thc samc logical mcaning lor thc UPAT statcmcnt
as it has lor thc !NSRT statcmcnt. xamplc 11.15 shows thc usc ol V!TH CHCK
PT!N with thc UPAT statcmcnt.
XAMPL 11.15
US samplc,
G
CRAT \!V v_100000
AS SLCT projcct_no, budgct
FRM projcct
VHR budgct ~ 100000
V!TH CHCK PT!N,
G
UPAT v_100000
ST budgct - 93000
VHR projcct_no - 'p3',
Cha pt er l l: vi ews 291
!n xamplc 11.15, atabasc nginc tcsts whcthcr thc modilicd valuc ol thc budget
column cvaluatcs to truc lor thc condition in thc VHR clausc ol thc SLCT
statcmcnt. Thc attcmptcd modilication lails bccausc thc condition is not mctthat is,
thc valuc 93000 is not grcatcr than thc valuc 100000.
Thc modilication ol columns in thc undcrlying tablcs is not possiblc il thc corrcsponding
vicw contains any ol thc lollowing lcaturcs:
column list includcs columns lrom morc than onc tablc
A column ol thc vicw is dcrivcd lrom an aggrcgatc lunction
!ST!NCT option
A column ol thc vicw is dcrivcd lrom a constant or an cxprcssion
xamplc 11.16 shows a vicw that cannot bc uscd to modily row valucs in thc
undcrlying basc tablc.
XAMPL 11.16
US samplc,
G
CRAT \!V v_uk_pound (projcct_numbcr, budgct_in_pounds)
AS SLCT projcct_no, budgct0.65
FRM projcct
VHR budgct ~ 100000,
G
SLCT
FRM v_uk_pound,
Thc rcsult is
pre[ect_acmher hc6qet_|a_peca6s
j I
j1 zzz!
Thc v_uk_pound vicw in xamplc 11.16 cannot bc uscd with an UPAT statcmcnt
(nor with an !NSRT statcmcnt) bccausc thc budget_in_pounds column is calculatcd
using an arithmctic cxprcssion, and thcrclorc docs not rcprcscnt an original column ol thc
undcrlying tablc.
292 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
DL7 Statement and a View
A vicw can bc uscd to dclctc rows ol a tablc that it dcpcnds on, as shown in xamplc 11.17.
XAMPL 11.17
US samplc,
G
CRAT \!V v_projcct_p1
AS SLCT cmp_no, job
FRM works_on
VHR projcct_no - 'p1',
G
LT FRM v_projcct_p1
VHR job - 'Clcrk',
xamplc 11.17 crcatcs a vicw that is thcn uscd to dclctc rows lrom thc works_on tablc.
Thc dclction ol rows in thc undcrlying tablcs is not possiblc il thc corrcsponding
vicw contains any ol thc lollowing lcaturcs:
column list includcs columns lrom morc than onc tablc
A column ol thc vicw is dcrivcd lrom an aggrcgatc lunction
!ST!NCT option
!n contrast to thc !NSRT and thc UPAT statcmcnts, thc LT statcmcnt
allows thc cxistcncc ol a constant or an cxprcssion in a column ol thc vicw that is uscd
to dclctc rows lrom thc undcrlying tablc.
xamplc 11.18 shows a vicw that can bc uscd to dclctc rows, but not to inscrt rows
or modily column valucs.
XAMPL 11.18
US samplc,
G
CRAT \!V v_budgct (budgct_rcduction)
AS SLCT budgct0.9
FRM projcct,
G
LT FRM v_budgct,
Cha pt er l l: vi ews 293
Thc LT statcmcnt in xamplc 11.18 dclctcs all rows ol thc project tablc,
which is rclcrcnccd by thc v_budget vicw.
Indexed Views
As you alrcady know lrom thc prcvious chaptcr, thcrc arc two spccial indcx typcs: indiccs
on computcd columns and indiccs on vicws. This chaptcr discusscs indiccs on vicws.
A vicw always contains a qucry that acts as a liltcr. Vithout indiccs crcatcd lor a
particular vicw, atabasc nginc builds dynamically thc rcsult sct lrom cach qucry
that rclcrcnccs a vicw. ("ynamically" mcans that il you modily thc contcnt ol a tablc,
thc corrcsponding vicw will always show thc ncw inlormation.) Also, il thc vicw
contains computations bascd on onc or morc columns ol thc tablc, thc computations arc
pcrlormcd cach timc you acccss thc vicw.
8uilding dynamically thc rcsult sct ol a qucry can dccrcasc pcrlormancc, il thc vicw
with its SLCT statcmcnt proccsscs many rows lrom onc or morc tablcs. !l such a vicw
is lrcqucntly uscd in qucrics, you could signilicantly incrcasc pcrlormancc by crcating a
clustcrcd indcx on thc vicw (scc thc ncxt scction). Crcating a clustcrcd indcx mcans that
thc systcm matcrializcs thc dynamic data into thc lcal pagcs on an indcx structurc.
atabasc nginc allows you to crcatc indiccs on vicws. Such vicws arc callcd indcxcd
or matcrializcd vicws. Vhcn a uniquc clustcrcd indcx is crcatcd on a vicw, thc vicw
is cxccutcd and thc rcsult sct is storcd in thc databasc in thc samc way a tablc with a
clustcrcd indcx is storcd. This mcans that thc lcal nodcs ol thc clustcrcd indcx's 8
trcc
contain data pagcs (scc also thc dcscription ol thc clustcrcd tablc in Chaptcr 10).
|s1ese1 ||eas c/e |m(|emes|e1 ||/ca| s,s|cs es|ess|css |c ||e t||/| ||||/ cs1 t||/| l|| s|c|emes|s. |s
||e t||/| ||||/ s|c|emes|, ,ca s(e:|/, ||e scme c/ c ||ea |ss|ec1 c/ c |c||e scme. |e s,s|cs c/ ||e t||/|
l|| s|c|emes| |s es|es1e1 a||| ||e :t||//3||||| :|case. |c/ mc/e |s/c/mc||cs cs es|ess|css |c |||s
s|c|emes|, see ||e 1es:/|(||cs c| ||e |e|ss|s c/ |||s :|c(|e/.
Creating an Indexed View
Crcating an indcxcd vicw is a twostcp proccss:
1. Crcatc thc vicw using thc CRAT \!V statcmcnt with thc V!TH
SCHMA8!N!NG clausc.
2. Crcatc thc corrcsponding clustcrcd indcx.
xamplc 11.19 shows thc lirst stcp, thc crcation ol a typical vicw that can bc indcxcd
to gain pcrlormancc. (This cxamplc assumcs that works_on is a vcry largc tablc.)
294 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
XAMPL 11.19
US samplc,
G
CRAT \!V v_cntcr_month
V!TH SCHMA8!N!NG
AS SLCT cmp_no, ATPART(MNTH, cntcr_datc) AS cntcr_month
FRM dbo.works_on,
Thc works_on tablc in thc sample databasc contains thc enter_date column, which
rcprcscnts thc starting datc ol an cmploycc in thc corrcsponding projcct. !l you want
to rctricvc all cmployccs that cntcrcd thcir projccts in a spccilicd month, you can usc
thc vicw in xamplc 11.19. To rctricvc such a rcsult sct using indcx acccss, atabasc
nginc cannot usc a tablc indcx, bccausc an indcx on thc enter_date column would
locatc thc valucs ol that column by thc datc, and not by thc month. !n such a casc,
indcxcd vicws can hclp, as xamplc 11.20 shows.
XAMPL 11.20
US samplc,
G
CRAT UN!QU CLUSTR !NX
c_workson_dcptno N v_cntcr_month (cntcr_month, cmp_no),
To makc a vicw indcxcd, you havc to crcatc a uniquc clustcrcd indcx on thc column(s)
ol thc vicw. (As prcviously alrcady statcd, a clustcrcd indcx is thc only indcx typc that
contains thc data valucs in its lcal pagcs.) Altcr you crcatc that indcx, thc databasc systcm
allocatcs storagc lor thc vicw, and thcn you can crcatc any numbcr ol nonclustcrcd indiccs
bccausc thc vicw is trcatcd as a (basc) tablc.
An indcxcd vicw can bc crcatcd only il thc lollowing options ol thc ST statcmcnt
arc sct to N (bccausc thc vicw must always display thc samc rcsult sct):
QUT_!NT!F!R
CNCAT_NULL_Y!LS_NULL
ANS!_NULLS
ANS!_PA!NG
ANS!_VARN!NGS
Also, thc NUMR!C_RUNA8RT option must bc sct to FF.
Cha pt er l l: vi ews 295
Thcrc arc scvcral ways to chcck whcthcr thc options in thc prcccding list arc
appropriatcly sct, as discusscd in thc upcoming scction "diting !nlormation
Conccrning !ndcxcd \icws."
To crcatc an indcxcd vicw, thc vicw dclinition has to mcct thc lollowing rcquircmcnts:
bc dctcrministicthat is, thcy must always rcturn thc samc rcsult lor thc samc
argumcnts.
to thc samc databasc.
SCHMA8!N!NG binds thc vicw to thc schcma ol thc undcrlying basc tablcs.
SCHMA8!N!NG option.
options: !ST!NCT, UN!N, CMPUT, TP, RR 8Y, M!N, MAX,
CUNT, SUM (on a nullablc cxprcssion), subqucrics, dcrivcd tablcs, or UTR.
Thc TransactSQL languagc allows you to vcrily all ol thcsc rcquircmcnts by using
thc sndexable paramctcr ol thc objectproperty propcrty lunction, as shown in
xamplc 11.21. !l thc valuc ol thc lunction is 1, all rcquircmcnts arc mct and you can
crcatc thc clustcrcd indcx.
XAMPL 11.21
US samplc,
SLCT objcctpropcrty(objcct_id('v_cntcr_month'), '!s!ndcxablc'),
Modifying tbe Structure of an Indexed View
To drop thc uniquc clustcrcd indcx on an indcxcd vicw, you havc to drop all
nonclustcrcd indiccs on thc vicw, too. Altcr you drop its clustcrcd indcx, thc vicw is
trcatcd by thc systcm as a convcnicnt vicw.
|/ ,ca 1/c( cs |s1ese1 ||ea, c|| |s1|:es cs ||c| ||ea c/e 1/c((e1.
296 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
!l you want to changc a standard vicw to an indcxcd onc, you havc to crcatc a uniquc
clustcrcd indcx on it. To do so, you must lirst spccily thc SCHMA8!N!NG option
lor that vicw. You can drop thc vicw and rccrcatc it, spccilying thc SCHMA8!N!NG
clausc in thc CRAT SCHMA statcmcnt, or you can crcatc anothcr vicw that has thc
samc tcxt as thc cxisting vicw but a dillcrcnt namc.
|/ ,ca :/ec|e c sea ||ea a||| c 1|//e/es| scme, ,ca mas| essa/e ||c| ||e sea ||ea mee|s c|| ||e /ea|/emes|s
/c/ cs |s1ese1 ||ea ||c| c/e 1es:/||e1 |s ||e (/e:e1|s se:||cs.
diting Information Concerning Indexed Views
You can usc thc sessionproperty propcrty lunction to tcst whcthcr onc ol thc options ol
thc ST statcmcnt is activatcd (scc thc carlicr scction "Crcating an !ndcxcd \icw" lor
a list ol thc options). !l thc lunction rcturns 1, thc sctting is N. xamplc 11.22 shows
thc usc ol thc lunction to chcck how thc QUT_!NT!F!R option is sct.
XAMPL 11.22
SLCT scssionpropcrty ('QUT_!NT!F!R'),
Thc casicr way is to usc thc dynamic managcmcnt vicw callcd sys.dm_exec_sessions,
bccausc you can rctricvc all valucs using only onc qucry. (Again, il thc valuc ol a column
is 1, thc corrcsponding option is sct to N.) xamplc 11.23 rcturns thc valuc lor thc
lirst lour ST statcmcnt options lrom thc list in "Crcating an !ndcxcd \icw." (Thc
global variablc spid is dcscribcd in Chaptcr 4.)
XAMPL 11.23
US samplc,
SLCT quotcd_idcntilicr, concat_null_yiclds_null, ansi_nulls, ansi_padding
FRM sys.dm_cxcc_scssions
VHR scssion_id - CCspid,
Thc sp_spaceused systcm proccdurc allows you to chcck whcthcr thc vicw
is matcrializcdthat is, whcthcr or not it uscs thc storagc spacc. Thc rcsult ol
xamplc 11.24 shows that thc v_enter_month vicw uscs storagc spacc lor thc data
as wcll as lor thc dclincd indcx.
XAMPL 11.24
US samplc,
XC sp_spaccuscd 'v_cntcr_month',
Cha pt er l l: vi ews 297
Thc rcsult is
aame rews resere6 6ata |a6ex_s|te cacse6
._eater_meat| || || || ||
8csidcs possiblc pcrlormancc gains lor complcx vicws that arc lrcqucntly rclcrcnccd in
qucrics, thc usc ol indcxcd vicws has two othcr advantagcs:
FRM clausc.
Probably thc most important propcrty ol indcxcd vicws is that a qucry docs not havc
to cxplicitly rclcrcncc a vicw to usc thc indcx on that vicw. !n othcr words, il thc qucry
contains rclcrcnccs to columns in thc basc tablc(s) that also cxist in thc indcxcd vicws,
and thc optimizcr cstimatcs that using thc indcxcd vicw is thc bcst choicc, it chooscs
thc vicw indiccs in thc samc way it chooscs tablc indiccs whcn thcy arc not dircctly
rclcrcnccd in a qucry.
Vhcn you crcatc an indcxcd vicw, thc rcsult sct ol thc vicw (at thc timc thc indcx
is crcatcd) is storcd on thc disk. Thcrclorc, all data that is modilicd in thc basc tablc(s)
will also bc modilicd in thc corrcsponding rcsult sct ol thc indcxcd vicw.
8csidcs all thc bcnclits that you can gain by using indcxcd vicws, thcrc is also
a (possiblc) disadvantagc: indiccs on indcxcd vicws arc usually morc complcx to
maintain than indiccs on basc tablcs, bccausc thc structurc ol a uniquc clustcrcd indcx
on an indcxcd vicw is morc complcx than a structurc ol thc corrcsponding indcx on a
basc tablc.
Thc lollowing typcs ol qucrics can achicvc signilicant pcrlormancc bcnclits il a vicw
that is rclcrcnccd by thc corrcsponding qucry is indcxcd:
Qucrics that proccss many rows and contain join opcrations or aggrcgatc
lunctions
Join opcrations and aggrcgatc lunctions that arc lrcqucntly pcrlormcd by onc or
scvcral qucrics
!l a qucry rclcrcnccs a standard vicw and thc databasc systcm has to proccss many
rows using thc join opcration, thc optimizcr will usually usc a suboptimal join mcthod.
Howcvcr, il you dclinc a clustcrcd indcx on that vicw, thc pcrlormancc ol thc qucry
298 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
could bc signilicantly cnhanccd, bccausc thc optimizcr can usc an appropriatc mcthod.
(Thc samc is truc lor aggrcgatc lunctions.)
!l a qucry that rclcrcnccs a standard vicw docs not proccss many rows, thc usc ol an
indcxcd vicw could still bc bcnclicial il thc qucry is uscd vcry lrcqucntly. (Thc samc is
truc lor groups ol qucrics that join thc samc tablcs or usc thc samc typc ol aggrcgatcs.)
!l thc rcstrictions on thc typcs ol vicws that can bc indcxcd might prcvcnt you lrom
using an indcxcd vicw in a particular qucry, try to crcatc partial solutionscach with
thc corrcsponding indcxcd vicwand, altcr that, union all partial solutions to an cntirc
onc. For instancc, you cannot dcsign an indcxcd vicw to proccss thc aggrcgation ol data
in tablcs lrom dillcrcnt databascs and with thc subscqucnt join ol thcir rcsults, bccausc
an indcxcd vicw cannot rclcrcncc tablcs lrom scvcral databascs. You can, howcvcr, crcatc
an indcxcd vicw in cach databasc that docs thc aggrcgation ol data. !l thc optimizcr can
match thc indcxcd vicw against all partial qucrics, at lcast thc aggrcgation proccssing
will spccd up. Vhilc thc join proccssing is not lastcr, thc ovcrall qucry is lastcr bccausc
it uscs thc aggrcgations storcd in thc indcxcd vicw.
ConcIusion
\icws can bc uscd lor dillcrcnt purposcs:
To rcstrict thc usc ol particular columns and/or rows ol tablcsthat is, to control
acccss to a particular part ol onc or morc tablcs
To hidc thc dctails ol complicatcd qucrics
To rcstrict inscrtcd and updatcd valucs to ccrtain rangcs
\icws arc crcatcd, rctricvcd, and modilicd with thc samc TransactSQL statcmcnts
that arc uscd to crcatc, rctricvc, and modily basc tablcs. Thc qucry on a vicw is always
translormcd into thc cquivalcnt qucry on an undcrlying basc tablc. An updatc opcration
is trcatcd in a manncr similar to a rctricval. Thc only dillcrcncc is that thcrc arc somc
rcstrictions on a vicw uscd lor inscrtion, modilication, and dclction ol data lrom a
tablc that it dcpcnds on. vcn so, thc way in which atabasc nginc handlcs thc
modilication ol rows and columns is morc systcmatic than thc way in which othcr
rclational databasc systcms handlc such modilication.
!ndcxcd vicws arc uscd to incrcasc pcrlormancc ol ccrtain qucrics. Vhcn a uniquc
clustcrcd indcx is crcatcd on a vicw, thc vicw bccomcs indcxcdthat is, its rcsult sct is
physically storcd in thc samc way a basc tablc is storcd.
Thc lollowing chaptcr cxplains in dctail thc sccurity issucs ol atabasc nginc.
Cha pt er l l: vi ews 299
xercises
.11.1
Crcatc a vicw that compriscs thc data ol all cmployccs that work lor thc dcpartmcnt d1.
.11.2
For thc projcct tablc, crcatc a vicw that can bc uscd by cmployccs who arc allowcd to
vicw all data ol this tablc cxccpt thc budget column.
.11.3
Crcatc a vicw that compriscs thc lirst and last namcs ol all cmployccs who cntcrcd thcir
projccts in thc sccond hall ol thc ycar 2007.
.11.4
Solvc xcrcisc .11.3 so that thc original columns f_name and l_name havc ncw
namcs in thc vicw: first and last, rcspcctivcly.
.11.5
Usc thc vicw in .11.1 to display lull dctails ol cvcry cmploycc whosc last namc bcgins
with thc lcttcr M.
.11.6
Crcatc a vicw that compriscs lull dctails ol all projccts on which thc cmploycc namcd
Smith works.
.11.7
Using thc ALTR \!V statcmcnt, modily thc condition in thc vicw in .11.1.
Thc modilicd vicw should comprisc thc data ol all cmployccs that work cithcr lor thc
dcpartmcnt d1 or d2, or both.
.11.8
clctc thc vicw crcatcd in .11.3. Vhat happcns with thc vicw crcatcd in .11.4:
.11.9
Using thc vicw lrom .11.2, inscrt thc dctails ol thc ncw projcct with thc projcct
numbcr p2 and thc namc Moon.
300 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
.11.10
Crcatc a vicw (with thc V!TH CHCK PT!N clausc) that compriscs thc lirst
and last namcs ol all cmployccs whosc cmploycc numbcr is lcss than 10,000. Altcr that,
usc thc vicw to inscrt data lor a ncw cmploycc namcd Kohn with thc cmploycc numbcr
22123, who works lor thc dcpartmcnt d3.
.11.11
Solvc xcrcisc .11.10 without thc V!TH CHCK PT!N clausc and lind thc
dillcrcnccs in rclation to thc inscrtion ol thc data.
.11.12
Crcatc a vicw (with thc V!TH CHCK PT!N clausc) with lull dctails lrom thc
works_on tablc lor all cmployccs that cntcrcd thcir projccts during thc ycars 2007 and
2008. Altcr that, modily thc cntcring datc ol thc cmploycc with thc cmploycc numbcr
29346. Thc ncw datc is 06/01/2006.
.11.13
Solvc xcrcisc .11.12 without thc V!TH CHCK PT!N clausc and lind thc
dillcrcnccs in rclation to thc modilication ol thc data.
In 7bis Cbapter
Autbentication
Scbemas
Database Security
RoIes
Autborization
7racking Cbanges
Data Security and Views
Sccurlty Systcm
ol Iatabasc Inglnc
Cbapter 12
Copyright 2008 by The McGraw-Hill Companies. Click here for terms of use.
302 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
T
his chaptcr bcgins with a bricl ovcrvicw ol thc most important conccpts ol
databasc sccurity. !t thcn discusscs thc spccilic lcaturcs ol thc sccurity systcm
ol atabasc nginc.
Thc lollowing arc thc most important databasc sccurity conccpts:
Authcntication
ncryption
Authorization
Tracking changcs
Authcntication rcquircs cvaluation ol thc lollowing qucstion: "ocs this uscr havc
a lcgitimatc right to acccss thc systcm :" Thcrclorc, this sccurity conccpt spccilics thc
proccss ol validating uscr crcdcntials to prcvcnt unauthorizcd uscrs lrom using a systcm.
Authcntication can bc chcckcd by rcqucsting thc uscr to providc, lor cxamplc:
Somcthing thc uscr is acquaintcd with (usually a password)
Somcthing thc uscr owns, such as a magnctic card or badgc
Authcntication is most commonly conlirmcd using a namc and a password. This
inlormation is cvaluatcd by thc systcm to dctcrminc whcthcr you arc thc uscr. This
proccss can bc strcngthcncd using cncryption.
ata cncryption is thc proccss ol scrambling inlormation so that it is incomprchcnsiblc
until it is dccryptcd by thc intcndcd rccipicnt. Scvcral mcthods can bc uscd to cncrypt
data, as discusscd in thc scction "ncryption" a bit latcr in this chaptcr.
Authorization is thc proccss that is applicd altcr thc idcntity ol a uscr is vcrilicd
through authcntication. uring this proccss, thc systcm dctcrmincs what rcsourccs
thc particular uscr can usc. !n othcr words, structural and systcm catalog inlormation
about a particular cntity is now availablc only to principalsthat is, subjccts that havc
pcrmission to acccss that cntity.
Tracking changcs mcans that actions ol unauthorizcd uscrs arc lollowcd and
documcntcd on your systcm. This proccss is usclul to protcct thc systcm against uscrs
with clcvatcd privilcgcs.
Thc lollowing scctions dcscribc in dctail all ol thc sccurity conccpts dclincd hcrc.
Additionally, thc cnd ol thc chaptcr dcscribcs how vicws can bc uscd to sccurc data.
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 303
Autbentication
atabasc nginc's sccurity systcm includcs two dillcrcnt sccurity subsystcms:
Vindows sccurity
SQL Scrvcr sccurity
Vindows sccurity spccilics sccurity at thc opcrating systcm lcvclthat is, thc
mcthod by which uscrs conncct to Vindows using thcir Vindows user accounts.
(Authcntication using this subsystcm is also callcd Vindows authcntication.)
SQL Scrvcr sccurity spccilics thc additional sccurity ncccssary at thc systcm lcvcl
that is, how uscrs who havc alrcady loggcd on to thc opcrating systcm can subscqucntly
conncct to thc databasc scrvcr. SQL Scrvcr sccurity dclincs a SQL Scrvcr login (also
callcd "login") that is crcatcd within thc systcm and is associatcd with a password. Somc
SQL Scrvcr logins arc idcntical to thc cxisting Vindows uscr accounts. (Authcntication
using this subsystcm is callcd SQL Scrvcr authcntication.)
|s c11|||cs |c |s1cas ase/ c::cas|s cs1 |c|ss, ||e/e c/e c|sc |s1cas /ca(s cs1 :9| :e/|e/ /c|es (c|sc
:c||e1 /c|es. / |s1cas /ca( |s c :c||e:||cs c/ |s1cas ase/ c::cas|s. /ss|s|s c ase/ c::cas| mem|e/s||(
|c c /ca( ||es ||e ase/ c|| ||e (e/m|ss|css /cs|e1 |c ||e /ca(. :|m||c/|,, c /c|e |s c :c||e:||cs c/ |c|ss. (|c|es
c/e 1|s:asse1 |s 1e|c|| |c|e/ |s |||s :|c(|e/.
8ascd on thcsc two sccurity subsystcms, atabasc nginc can opcratc in onc ol
lollowing authcntication modcs:
Vindows modc
Mixcd modc
Vindows modc rcquircs uscrs to usc Vindows uscr accounts cxclusivcly to log in to
thc systcm. Thc systcm acccpts thc uscr account, assuming it has alrcady bccn validatcd
at thc opcrating systcm lcvcl. This kind ol conncction to a databasc systcm is callcd a
trusted connection, bccausc thc systcm trusts that thc opcrating systcm alrcady validatcd
thc account and thc corrcsponding password.
Mixcd modc allows uscrs to conncct to atabasc nginc using Vindows authcntication
or SQL Scrvcr authcntication. This mcans that somc uscr accounts can bc sct up to usc
thc Vindows sccurity subsystcm, whilc othcrs can bc sct up to usc both thc SQL Scrvcr
sccurity subsystcm and thc Vindows sccurity subsystcm.
304 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
:9| :e/|e/ ca||es||:c||cs |s (/c||1e1 /c/ |c:|ac/1 :cm(c|||||||, cs|,. |c/ |||s /ecscs, ase |s1cas
ca||es||:c||cs |ss|ec1.
ImpIementing an Autbentication Mode
You usc SQL Scrvcr Managcmcnt Studio to choosc onc ol thc cxisting authcntication
modcs. (Chaptcr 3 discusscs thc SQL Scrvcr Managcmcnt Studio intcrlacc in dcpth.)
To sct up Vindows modc, rightclick thc scrvcr and click Properties. !n thc Server
Properties dialog box, choosc thc Security pagc and click Windows Authentication
Mode. To choosc Mixcd modc, thc only dillcrcncc is that you havc to click SQL
Server and Windows Authentication Mode in thc Server Properties dialog box.
Altcr a uscr succcsslully connccts to atabasc nginc, thc uscr's acccss to databasc
objccts is indcpcndcnt ol whcthcr Vindows authcntication or SQL Scrvcr authcntication
is uscd.
8clorc you lcarn how to sct databasc scrvcr sccurity, you nccd to undcrstand cncryption
policics and mcchanisms, discusscd ncxt.
ncrypting Data
atabasc nginc sccurcs data with hicrarchical cncryption laycrs and a kcy managcmcnt
inlrastructurc. ach laycr sccurcs thc laycr bcncath it, using a combination ol ccrtilicatcs,
asymmctric kcys, and symmctric kcys (scc Figurc 121).
Thc scrvicc mastcr kcy in Figurc 121 spccilics thc kcy that rulcs all othcr kcys and
ccrtilicatcs. Thc scrvicc mastcr kcy is crcatcd automatically whcn you install atabasc
nginc. (This kcy is cncryptcd using thc Vindows ata Protcction AP! (PAP!).
Thc important propcrty ol thc scrvicc mastcr kcy is that it is managcd by thc systcm.
Although thc systcm administrator can pcrlorm scvcral maintcnancc tasks, thc only onc
task, which should bc donc, is to back up thc scrvicc mastcr kcy, so you can rcstorc thc
kcy, il it is corruptcd.
As you can scc in Figurc 121, thc databasc mastcr kcy is thc root cncryption objcct
lor all kcys, ccrtilicatcs, and data at thc databasc lcvcl. ach databasc has a singlc
databasc mastcr kcy, which is crcatcd using thc CRAT MASTR KY statcmcnt.
8ccausc thc databasc mastcr kcy is protcctcd by thc scrvicc mastcr kcy, it is possiblc lor
thc systcm to automatically dccrypt thc databasc mastcr kcy.
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 305
ncc thc databasc mastcr kcy cxists, uscrs can usc it to crcatc uscr kcys, which arc
crcatcd and manipulatcd by uscrs. Thcrc arc thrcc lorms ol uscr kcys: symmctric kcys,
asymmctric kcys, and ccrtilicatcs. Thc lollowing subscctions dcscribc thc uscr kcys.
Symmetric keys
An cncryption systcm that uscs symmctric kcys is onc in which thc scndcr and rcccivcr
ol a mcssagc sharc a common kcy. Thus, this singlc kcy is uscd lor both cncryption and
dccryption.
Using symmctric kcys has scvcral bcnclits and onc disadvantagc. nc advantagc ol
using symmctric kcys is that thcy can protcct a signilicantly grcatcr amount ol data
than can thc othcr two typcs ol uscr kcys. Also, using this kcy typc is signilicantly lastcr
than using an asymmctric kcy.
n thc othcr hand, in a distributcd cnvironmcnt, using this typc ol kcy can makc it
almost impossiblc to kccp cncryption sccurc, bccausc thc samc kcy is uscd to dccrypt and
cncrypt data on both cnds. So, thc gcncral rccommcndation is that symmctric kcys should
bc uscd only with applications in which data is storcd as cncryptcd tcxt at onc placc.
||qcre 11-1 |c|c|cse |s|se. ||e ||e/c/:||:c| es:/,(||cs |c,e/s
Service
Master Key
encrypted
with DPAPI
Windows
level
SQL Server
level
Database
level
Service
Master Key
Database
Master Key
Asymmetric
Keys
Symmetric
Keys
Data
Certificates
Symmetric
Keys
Data
Symmetric
Keys
Data
306 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Thc TransactSQL languagc supports scvcral statcmcnts and systcm lunctions rclatcd to
symmctric kcys. Thc CRAT SYMMTR!C KY statcmcnt crcatcs a ncw symmctric
kcy, whilc thc RP SYMMTR!C KY rcmovcs an cxisting symmctric kcy. ach
symmctric kcy must bc opcncd bclorc you can usc it to cncrypt data or protcct anothcr
ncw kcy. Thcrclorc, you usc thc PN SYMMTR!C KY statcmcnt to opcn a kcy.
Altcr you opcn a symmctric kcy, you nccd to usc thc EncryptByKey systcm lunction
lor cncryption. This lunction has two input paramctcrs: thc ! ol thc kcy and tcxt,
which has to bc cncryptcd. For dccryption, you usc thc DecryptByKey lunction.
:ee 3cc|s 0s||se /c/ 1e|c||e1 1es:/|(||css c/ c|| /cssc:|-:9| s|c|emes|s /e|c|e1 |c s,mme|/|: |e,s cs ae|| cs ||e
s,s|em /as:||css fact,t8,ke, cs1 0ect,t8,ke,.
Asymmetric keys
!l you havc a distributcd cnvironmcnt or il a symmctric kcy docs not kccp your
cncryption sccurc, usc asymmctric kcys. An asymmctric kcy consists ol two parts: a
privatc kcy and thc corrcsponding public kcy. ach kcy can dccrypt data cncryptcd by
thc othcr kcy. 8ccausc ol thc cxistcncc ol a privatc kcy, asymmctric cncryption providcs
a highcr lcvcl ol sccurity than docs symmctric cncryption.
Thc TransactSQL languagc supports scvcral statcmcnts and systcm lunctions
rclatcd to asymmctric kcys. Thc CRAT ASYMMTR!C KY statcmcnt crcatcs a
ncw asymmctric kcy, whilc thc ALTR ASYMMTR!C KY statcmcnt changcs thc
propcrtics ol an asymmctric kcy. Thc RP ASYMMTR!C KY statcmcnt drops
an cxisting asymmctric kcy.
Altcr you crcatc an asymmctric kcy, usc thc EncryptByAsymKey systcm lunction to
cncrypt data. This lunction has two input paramctcrs: thc ! ol thc kcy and tcxt, which
has to bc cncryptcd. For dccryption, usc thc DecryptByAsymKey lunction.
:ee 3cc|s 0s||se /c/ 1e|c||e1 1es:/|(||css c/ c|| /cssc:|-:9| s|c|emes|s /e|c|e1 |c cs,mme|/|: |e,s cs ae|| cs
||e s,s|em /as:||css fact,t8,4s,mke, cs1 0ect,t8,4s,mke,.
Certificates
A public kcy ccrtilicatc, usually simply callcd a ccrtilicatc, is a digitally signcd statcmcnt
that binds thc valuc ol a public kcy to thc idcntity ol thc pcrson, dcvicc, or scrvicc that
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 307
holds thc corrcsponding privatc kcy. Ccrtilicatcs arc issucd and signcd by a ccrtilication
authority (CA). Thc cntity that rcccivcs a ccrtilicatc lrom a CA is thc subjcct ol that
ccrtilicatc. Ccrtilicatcs contain thc lollowing inlormation.
A primary bcnclit ol ccrtilicatcs is that thcy rclicvc hosts ol thc nccd to maintain
a sct ol passwords lor individual subjccts. Vhcn a host, such as a sccurc wcb scrvcr,
dcsignatcs an issucr as a trustcd authority, thc host implicitly trusts that thc issucr has
vcrilicd thc idcntity ol thc ccrtilicatc subjcct.
te/||/|:c|es (/c||1e ||e |||es| |e|e| c/ es:/,(||cs |s ||e |c|c|cse |s|se se:a/||, mc1e|. |e es:/ ,(||cs
c|c/|||ms /c/ :e/||/|:c|es c/e |e/, (/c:essc/-|s|ess||e. |c/ |||s /ecscs, ase :e/||/|:c|es s(c/|s| ,.
Thc most important statcmcnt rclatcd to ccrtilicatcs is thc CRAT CRT!F!CAT
statcmcnt. xamplcs 12.1 and 12.2 show thc usc ol this statcmcnt.
XAMPL 12.1
US samplc,
CRAT MASTR KY
NCRYPT!N 8Y PASSVR - 'p1s4w9d16'
G
CRAT CRT!F!CAT ccrt01
V!TH SU8JCT - 'Ccrtilicatc lor dbo',
!l you want to crcatc a ccrtilicatc without thc NCRYPT!N 8Y option, you havc
lirst to crcatc thc databasc mastcr kcy. (ach CRAT CRT!F!CAT statcmcnt that
docs not includc this option is protcctcd by thc databasc mastcr kcy.) For this rcason, thc
lirst statcmcnt in xamplc 12.1 is thc CRAT MASTR KY statcmcnt. Altcr that,
thc CRAT CRT!F!CAT statcmcnt is uscd to crcatc a ncw ccrtilicatc, cert01,
which is owncd by dbo in thc sample databasc, il thc currcnt uscr is dbo.
308 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
XAMPL 12.2
US samplc,
CRAT CRT!F!CAT ccrt02
NCRYPT!N 8Y PASSVR - 'pGF4bb92Gvbd2439587y'
V!TH SU8JCT - 'SQL Scrvcr 2008',
xamplc 12.2 crcatcs thc ncw ccrtilicatc callcd cert02. Thc NCRYPT!N 8Y
PASSVR option spccilics thc password that will bc uscd to cncrypt thc privatc kcy.
ncryption CataIog Views
Thc most important cncryption catalog vicws arc thc lollowing:
sys.symmctric_kcys
sys.asymmctric_kcys
sys.databasc_principals
Thc lirst thrcc catalog vicws providc inlormation about all symmctric kcys, all
asymmctric kcys, and all thc ccrtilicatcs installcd in thc currcnt databasc, rcspcctivcly.
Thc sys.database_principals catalog vicw providcs inlormation about cach ol thc
principals in thc currcnt databasc. (You can join thc last catalog vicw with any ol thc
thrcc othcrs to scc inlormation about who owns a particular kcy.)
SQL Server 2008 ncryption nhancements
SQL Scrvcr 2008 supports two ncw cncryption lcaturcs:
xtcnsiblc Kcy Managcmcnt (KM)
Transparcnt ata ncryption (T)
KM allows thirdparty vcndors to rcgistcr thcir dcviccs in atabasc nginc. ncc
thc dcviccs arc rcgistcrcd, SQL Scrvcr logins can usc thc cncryption kcys storcd on thcsc
modulcs as wcll as lcvcragc advanccd cncryption lcaturcs that thcsc modulcs support. KM
also allows data protcction lrom databasc administrators (cxccpt mcmbcrs ol thc sysadmin
group). That way, you can protcct thc systcm against uscrs with clcvatcd privilcgcs. ata
can bc cncryptcd and dccryptcd using TransactSQL cryptographic statcmcnts, and SQL
Scrvcr uscs thc cxtcrnal KM dcvicc as thc kcy storc.
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 309
Thc lollowing TransactSQL statcmcnts support KM:
CREATE CRYPTOGRAPHC PROVDER Crcatcs a cryptographic
providcr within atabasc nginc lrom a thirdparty KM vcndor
DROP CRYPTOGRAPHC PROVDER rops an cxisting providcr
0s|, ||e |s|e/(/|se cs1 |e|e|c(e/ e1|||css c/ :9| :e/|e/ 1^^? sa((c/| ||/.
Transparcnt ata ncryption introduccs a ncw databasc option that cncrypts thc
databasc lilcs automatically, without nccding to altcr any applications. That way, you can
prcvcnt thc databasc acccss ol unauthorizcd pcrsons, cvcn il thcy obtain thc databasc
lilcs or databasc backup lilcs.
ncryption ol thc databasc lilc is pcrlormcd at thc pagc lcvcl. Thc pagcs in an
cncryptcd databasc arc cncryptcd bclorc thcy arc writtcn to disk and dccryptcd whcn
thcy arc rcad into mcmory. Transparcnt data cncryption docs not incrcasc thc sizc ol
thc cncryptcd databasc.
Setting Up System Security Using DDL
Thc sccurity ol atabasc nginc can bc sct up using cithcr TransactSQL statcmcnts
or systcm proccdurcs. This scction discusscs only TransactSQL statcmcnts, bccausc
all corrcsponding systcm proccdurcs (sp_addlogin and sp_droplogin) arc dcprccatcd
lcaturcs and will bc rcmovcd in onc ol thc lollowing vcrsions ol SQL Scrvcr. Thc thrcc
TransactSQL statcmcnts arc CRAT LG!N, ALTR LG!N, and RP
LG!N.
Thc CRAT LG!N statcmcnt crcatcs a ncw SQL Scrvcr login. Thc syntax is
as lollows:
CRAT LG!N login_namc
[ V!TH option_list1 ]
FRM [V!NVS | V!TH option_list2 |,...| |
] CRT!F!CAT ccrtnamc ] ASYMMTR!C KY kcy_namc ]]
login_name spccilics thc namc ol thc login that is bcing crcatcd. As you can scc
lrom thc syntax ol thc statcmcnt, you can usc thc V!TH clausc to spccily onc or morc
options lor thc login or usc thc FRM clausc to dclinc a ccrtilicatc, asymmctric kcy, or
Vindows uscr account associatcd with thc corrcsponding login.
310 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
option_list1 contains scvcral options. Thc most important onc is thc PASSVR
option, which spccilics thc password ol thc login (scc xamplc 12.3). (Thc othcr possiblc
options arc FAULT_ATA8AS, FAULT_LANGUAG, and CHCK_
XP!RAT!N.)
As you can scc lrom thc syntax ol thc CRAT LG!N statcmcnt, thc FRM
clausc contains onc ol thc lollowing options:
WNDOWS option
suboptions, such as FAULT_ATA8AS and FAULT_LANGUAG.
CERTICATE option
with this login.
ASYMMETRC KEY option
alrcady cxist in thc master databasc.)
Thc lollowing cxamplcs show thc crcation ol dillcrcnt login lorms. xamplc 12.3
spccilics thc login callcd mary, with thc password you1know4it9.
XAMPL 12.3
US samplc,
CRAT LG!N mary V!TH PASSVR - 'you1know4it9',
xamplc 12.4 crcatcs thc login callcd pete, which will bc mappcd to a Vindows uscr
account with thc samc namc.
XAMPL 12.4
US samplc,
CRAT LG!N |NT811901\pctc| FRM V!NVS,
ca |c|e |c c||e/ ||e ase/scme cs1 ||e :cm(a|e/ scme c::c/1|s |c ,ca/ es||/csmes|.
Thc sccond sccurity statcmcnt supportcd by TransactSQL is ALTR LG!N, which
changcs thc propcrtics ol a particular login. Using thc ALTR LG!N statcmcnt, you can
changc thc currcnt password and its cxpiration propcrtics, crcdcntials, dclault databasc, and
dclault languagc. You can also cnablc or disablc thc spccilicd login.
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 311
Finally, thc RP LG!N statcmcnt drops an cxisting login. A login cannot bc
droppcd il it rclcrcnccs (owns) othcr objccts.
Managing Logins Using Management Studio
To crcatc a ncw login using SQL Scrvcr Managcmcnt Studio, cxpand thc scrvcr,
cxpand Security, rightclick Logins, and click New Login. Thc Login dialog box
(scc Figurc 122) appcars. First, you havc to dccidc bctwccn Vindows authcntication
and SQL Scrvcr authcntication. !l you choosc Vindows authcntication, thc login
namc must bc a valid Vindows namc, which is writtcn in thc lorm domain\user_
name. !l you choosc SQL Scrvcr authcntication, you havc to typc thc ncw login namc
and thc corrcsponding password. ptionally, you may also spccily thc dclault databasc
and languagc lor thc ncw login. (Thc dclault databasc is thc databasc that thc uscr is
automatically conncctcd to immcdiatcly altcr logging in to atabasc nginc.) Altcr
that, thc uscr can log in to thc systcm undcr thc ncw account.
||qcre 11-1 |c|s 1|c|c |cs
312 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Scbemas
atabasc nginc uscs schcmas in its sccurity modcl to simplily thc rclationship bctwccn
uscrs and objccts, and thus schcmas havc a vcry big impact on how you intcract with
atabasc nginc.. This scction dcscribcs thc rolc ol schcmas in atabasc nginc sccurity.
Thc lirst subscction dcscribcs thc rclationship bctwccn schcmas and uscrs, thc sccond
subscction discusscs all thrcc Transact SQL statcmcnts rclatcd to schcma crcation and
modilication.
User-Scbema Separation
A schcma is a collcction ol databasc objccts that is owncd by a singlc pcrson and lorms
a singlc namcspacc. (Two tablcs in thc samc schcma cannot havc thc samc namc.) Sincc
SQL Scrvcr 2005, thc tight rclationship bctwccn uscrs and schcmas has bccn brokcn.
Now, atabasc nginc supports namcd schcmas using thc notion ol a principal, an cntity
that can acccss objccts. A principal can bc cithcr ol thc lollowing:
An indivisiblc principal
A group principal
An indivisiblc principal rcprcscnts a singlc uscr, such as a login or Vindows uscr
account. A group principal can bc a group ol uscrs, such as a rolc or Vindows group.
Principals arc owncrships ol schcmas, but thc owncrship ol a schcma can bc translcrrcd
casily to anothcr principal and without changing thc schcma namc.
Thc scparation ol databasc uscrs lrom schcmas providcs signilicant bcnclits, such as:
nc principal can own scvcral schcmas.
Scvcral indivisiblc principals can own a singlc schcma via mcmbcrship in rolcs or
Vindows groups.
ropping a databasc uscr docs not rcquirc thc rcnaming ol objccts containcd by
that uscr's schcma.
ach databasc has a dclault schcma, which is uscd to rcsolvc thc namcs ol objccts that
arc rclcrrcd to without thcir lully qualilicd namcs. Thc dclault schcma spccilics thc lirst
schcma that will bc scarchcd by thc databasc scrvcr whcn it rcsolvcs thc namcs ol objccts.
Thc dclault schcma can bc sct and changcd using thc FAULT_SCHMA option
ol thc CRAT USR or ALTR USR statcmcnt. !l FAULT_SCHMA is lclt
undclincd, thc databasc uscr will havc dbo as its dclault schcma. (All dclault schcmas arc
dcscribcd in dctail in thc scction "clault atabasc Schcmas" latcr in this chaptcr.)
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 313
DDL Scbema-ReIated Statements
Thcrc arc thrcc TransactSQL schcmarclatcd statcmcnts:
CRAT SCHMA
ALTR SCHMA
RP SCHMA
CRA7 SCHMA
xamplc 12.5 shows how schcmas can bc crcatcd and uscd to control databasc sccurity.
3e/c/e ,ca s|c/| |scm(|e !1.:, ,ca |c|e |c :/ec|e 1c|c|cse ase/s etet cs1 met,. |c/ |||s /ecscs, /|/s| ese:a|e
||e /cssc:|-:9| s|c|emes|s |s |scm(|e !1.?.
XAMPL 12.5
US samplc,
G
CRAT SCHMA my_schcma AUTHR!ZAT!N pctcr
G
CRAT TA8L product
(product_no CHAR(10) NT NULL UN!QU,
product_namc CHAR(20) NULL,
pricc MNY NULL),
G
CRAT \!V product_inlo
AS SLCT product_no, product_namc
FRM product,
G
GRANT SLCT T mary,
NY UPAT T mary,
xamplc 12.5 crcatcs thc my_schema schcma, which compriscs thc product
tablc and thc product_info vicw. Thc databasc uscr callcd peter is thc databasclcvcl
principal that owns thc schcma. (You usc thc AUTHR!ZAT!N option to dclinc
thc principal ol a schcma. Thc principal may own othcr schcmas and may not usc thc
currcnt schcma as his or hcr dclault schcma.)
314 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
|e |ac c||e/ s|c|emes|s :cs:e/s|s (e/m|ss|css c/ 1c|c|cse c|(e:|s, |/| cs1 |||, c/e 1|s:asse1 |s 1e|c||
c| ||e es1 c/ |||s :|c(|e/. |/| /cs|s ||e :|||t (e/m|ss|css /c/ c|| c|(e:|s :/ec|e1 |s ||e s:|emc, a|||e |||
1es|es ||e |||/| (e/m|ss|css /c/ c|| c|(e:|s c/ ||e s:|emc.
Thc CRAT SCHMA statcmcnt can crcatc a schcma, crcatc thc tablcs and vicws
it contains, and grant, rcvokc, or dcny pcrmissions on a sccurablc in a singlc statcmcnt.
:e:a/c||es c/e /esca/:es |c a||:| ||e :9| :e/|e/ ca||c/|cc||cs s,s|em /ea|c|es c::ess. |e/e c/e ||/ee mc|s
se:a/c||e s:c(es. se/|e/, 1c|c|cse, cs1 s:|emc, a||:| :cs|c|s c||e/ se:a/c||es, sa:| as |c|ss, 1c|c|cse ase/s,
|c||es, cs1 s|c/e1 (/c:e1a/es.
Thc CRAT SCHMA statcmcnt is atomic. !n othcr words, il any crror occurs
during thc cxccution ol a CRAT SCHMA statcmcnt, nonc ol thc TransactSQL
statcmcnts spccilicd in thc schcma will bc cxccutcd.
atabasc objccts that arc crcatcd in a CRAT SCHMA statcmcnt can bc
spccilicd in any ordcr, with onc cxccption: a vicw that rclcrcnccs anothcr vicw must bc
spccilicd altcr thc rclcrcnccd vicw.
A databasclcvcl principal could bc a databasc uscr, rolc, or application rolc. (Rolcs
and application rolcs arc discusscd in thc "Rolcs" scction latcr in thc chaptcr.) Thc
principal that is spccilicd in thc AUTHR!ZAT!N clausc ol thc CRAT
SCHMA statcmcnt is thc owncr ol all objccts crcatcd within thc schcma. wncrship
ol schcmacontaincd objccts can bc translcrrcd to any othcr databasclcvcl principal
using thc ALTR AUTHR!ZAT!N statcmcnt (scc xamplc 12.7).
Thc uscr nccds thc CRAT SCHMA pcrmission on thc databasc to cxccutc thc
CRAT SCHMA statcmcnt. Also, to crcatc thc objccts spccilicd within thc CRAT
SCHMA statcmcnt, thc uscr nccds thc corrcsponding CRAT pcrmissions.
AL7R SCHMA
Thc ALTR SCHMA statcmcnt translcrs an objcct bctwccn dillcrcnt schcmas ol
thc samc databasc. Thc syntax ol thc ALTR SCHMA statcmcnt is as lollows:
ALTR SCHMA schcma_namc TRANSFR objcct_namc
xamplc 12.6 shows thc usc ol thc ALTR SCHMA statcmcnt.
XAMPL 12.6
US AdvcnturcVorks,
ALTR SCHMA humanrcsourccs TRANSFR pcrson.addrcss,
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 315
xamplc 12.6 altcrs thc schcma callcd humanresources ol thc AdventureWorks
databasc by translcrring into it thc address tablc lrom thc person schcma ol thc samc
databasc.
Thc ALTR SCHMA statcmcnt can only bc uscd to translcr objccts bctwccn
dillcrcnt schcmas in thc samc databasc. (Singlc objccts within a schcma can bc altcrcd
using thc ALTR TA8L statcmcnt or thc ALTR \!V statcmcnt.)
DROP SCHMA
Thc RP SCHMA statcmcnt rcmovcs a schcma lrom thc databasc. You can
succcsslully cxccutc thc RP SCHMA statcmcnt lor a schcma only il thc schcma
docs not contain any objccts. !l thc schcma contains any objccts, thc RP SCHMA
statcmcnt will bc rcjcctcd by thc systcm.
As prcviously statcd, thc systcm allows you to changc thc owncrship ol a schcma
by using thc ALTR AUTHR!ZAT!N statcmcnt. This statcmcnt modilics thc
owncrship ol an cntity.
|e /cssc:|-:9| |csace 1ces sc| sa((c/| ||e t||/| /||0||//|0| cs1 ||0| /||0||//|0| s|c|emes|s.
ca s(e:|/, ||e case/s||( c/ cs es|||, |, as|s ||e t||/| :t||// s|c|emes|.
xamplc 12.7 shows thc usc ol thc ALTR AUTHR!ZAT!N statcmcnt to
changc thc owncrship ol thc my_schema schcma.
XAMPL 12.7
US samplc,
ALTR AUTHR!ZAT!N N SCHMA ::my_schcma T mary,
Database Security
A Vindows uscr account or a login allows a uscr to log in to thc systcm. A uscr who
subscqucntly wants to acccss a particular databasc ol thc systcm also nccds a databasc
uscr account to work with thc databasc. Thcrclorc, uscrs must havc a databasc uscr
account lor cach databasc thcy want to usc. Thc databasc uscr account can bc mappcd
lrom thc cxisting Vindows uscr accounts, Vindows groups (ol which thc uscr is a
mcmbcr), logins, or rolcs.
316 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Setting Up Database User Accounts
atabasc sccurity pcrmissions can bc sct up using TransactSQL statcmcnts, Managcmcnt
Studio, or systcm proccdurcs. This scction docs not cxplain how to sct up uscr accounts
with systcm proccdurcs, bccausc all corrcsponding systcm proccdurcs (sp_grantdbacccss
and sp_rcvokcdbacccss) will bc rcmovcd in a luturc vcrsion ol SQL Scrvcr.
Adding Users Using 7ransact-SQL Statements
Thc CRAT USR statcmcnt adds a uscr to thc currcnt databasc. Thc syntax ol this
statcmcnt is
CRAT USR uscr_namc
|FR [LG!N login ]CRT!F!CAT ccrt_namc ]ASYMMTR!C KY kcy_namc]|
| V!TH FAULT_SCHMA - schcma_namc |
user_name is thc namc that is uscd to idcntily thc uscr insidc thc databasc. login
spccilics thc login lor which thc uscr is bcing crcatcd. cert_name and key_name spccily
thc corrcsponding ccrtilicatc and asymmctric kcy, rcspcctivcly. Finally, thc V!TH
FAULT SCHMA option spccilics thc lirst schcma that will bc scarchcd by thc
scrvcr whcn it rcsolvcs thc namcs ol objccts lor this databasc uscr.
xamplc 12.8 dcmonstratcs thc usc ol thc CRAT USR statcmcnt.
XAMPL 12.8
US samplc,
CRAT USR pctcr FR LG!N |NT811901\pctc|,
CRAT USR mary FR LG!N mary V!TH FAULT_SCHMA -
my_schcma,
c ese:a|e ||e /|/s| s|c|emes| sa::ess/a||,, :/ec|e ||e |s1cas c::cas| scme1 ete cs1 :|cse ||e se/|e/ scme.
Thc lirst CRAT USR statcmcnt crcatcs thc databasc uscr callcd peter lor
thc Vindows login callcd pete. pete will usc dbo as its dclault schcma, bccausc thc
FAULT SCHMA option is omittcd. (clault schcmas will bc dcscribcd in thc
scction "clault atabasc Schcmas" latcr in this chaptcr.)
Thc sccond CRAT USR statcmcnt crcatcs a ncw databasc uscr with thc namc
mary. This uscr has my_schema as hcr dclault schcma. (Thc FAULT_SCHMA
option can bc sct to a schcma that docs not currcntly cxist in thc databasc.)
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 317
|c:| 1c|c|cse |cs ||s cas s(e:|/|: ase/s. |e/e/c/e, ||e t||/| |:|| s|c|emes| mas| |e ese:a|e1 cs:e /c/ ec:|
1c|c|cse a|e/e c ase/ c::cas| s|ca|1 es|s|. /|sc, c :9| :e/|e/ |c|s :cs |c|e cs|, c :c//es(cs1|s
1c|c|cse ase/ /c/ c ||es 1c|c|cse.
Thc ALTR USR statcmcnt modilics a databasc uscrnamc, changcs its dclault
schcma, or rcmaps a uscr to anothcr login. Similar to thc CRAT USR statcmcnt, it
is possiblc to assign a dclault schcma to a uscr bclorc thc crcation ol thc schcma.
Thc RP USR statcmcnt rcmovcs a uscr lrom thc currcnt databasc. Uscrs that
own sccurablcs (that is, databasc objccts) cannot bc droppcd lrom thc databasc.
Adding Users Using SQL Server Management Studio
To add uscrs to a databasc using SQL Scrvcr Managcmcnt Studio, cxpand thc scrvcr,
cxpand thc Databases loldcr, cxpand thc databasc, and cxpand Security. Rightclick
Users and click New User. !n thc Database User dialog box (scc Figurc 123), cntcr a
uscrnamc and choosc a corrcsponding login namc. ptionally, you can choosc databasc
rolc mcmbcrships and schcmas owncd by this uscr.
||qcre 11-1 |c|c|cse |se/ 1|c|c |cs
318 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
DefauIt Database Scbemas
ach databasc within thc systcm has thc lollowing dclault databasc schcmas:
gucst
dbo
!NFRMAT!N_SCHMA
sys
atabasc nginc allows uscrs without uscr accounts to acccss a databasc using thc
guest schcma. (Altcr crcation, cach databasc contains this schcma.) You can apply
pcrmissions to thc guest schcma in thc samc way as you apply thcm to any othcr
schcma. Also, you can drop and add thc gucst schcma lrom any databasc cxccpt thc
master and tempdb systcm databascs.
ach databasc objcct bclongs to onc and only onc schcma, which is thc dclault
schcma lor that objcct. Thc dclault schcma can bc dclincd cxplicitly or implicitly. !l
thc dclault schcma isn't dclincd cxplicitly during thc crcation ol an objcct, that objcct
bclongs to thc dbo schcma. Also, thc login that is thc owncr ol a databasc always has
thc spccial uscrnamc dbo whcn using thc databasc it owns.
Thc !NFRMAT!N_SCHMA schcma contains all inlormation schcma vicws.
Thc sys schcma, as you may havc alrcady gucsscd, contains systcm objccts, such as
catalog vicws.
RoIes
Vhcn scvcral uscrs nccd to pcrlorm similar activitics in a particular databasc (and thcrc
is no corrcsponding Vindows group), you can add a database role, which spccilics a
group ol databasc uscrs that can acccss thc samc objccts ol thc databasc.
Mcmbcrs ol a databasc rolc can bc any ol thc lollowing:
Vindows groups and uscr accounts
SQL Scrvcr logins
thcr rolcs
Thc sccurity architccturc in atabasc nginc includcs scvcral "systcm" rolcs that
havc spccial implicit pcrmissions. Thcrc arc two typcs ol prcdclincd rolcs (in addition to
uscrdclincd rolcs):
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 319
Fixcd scrvcr rolcs
Fixcd databasc rolcs
8csidc thcsc two, thc lollowing scctions also dcscribc thc lollowing typcs ol rolcs:
Application rolcs
Fixed Server RoIes
Fixcd scrvcr rolcs arc dclincd at thc scrvcr lcvcl and thcrclorc cxist outsidc ol databascs
bclonging to thc databasc scrvcr. Tablc 121 lists all cxisting lixcd scrvcr rolcs.
Thc lollowing two systcm proccdurcs arc uscd, rcspcctivcly, to add mcmbcrs to and
dclctc mcmbcrs lrom a lixcd scrvcr rolc:
sp_addsrvrolcmcmbcr
sp_dropsrvrolcmcmbcr
ca :cssc| c11 c/ /emc|e /|se1 se/|e/ /c|es. /11|||csc||,, cs|, ||e mem|e/s c/ /|se1 se/|e/ /c|es :cs ese:a|e ||e
s,s|em (/c:e1a/es |c c11 c/ /emc|e |c|ss |c c/ //cm ||e /c|e.
ach lixcd scrvcr rolc has its implicit pcrmissions within a databasc systcm. You can
vicw thc pcrmissions lor cach lixcd scrvcr rolc using thc sp_srvrolepermission systcm
proccdurc. Usc 8ooks nlinc to lcarn morc about lixcd scrvcr rolcs and thcir pcrmissions.
||xe6 !erer ke|e 0escr|pt|ea
..+am|a |erlerm. +a +ct|.|t |a t|e a+t+|+.e ..tem
.er.er+am|a Ceal|are. .er.er .ett|a.
.etaj+am|a |a.t+||. rej||c+t|ea +aa m+a+e. e\teaaea jreceaare.
.ecar|t+am|a M+a+e. |e|a. +aa C|||I| ||I|||:| jerm|..|ea. +aa re+a. +aa|t.
jrece..+am|a M+a+e. ..tem jrece..e.
a|cre+ter Cre+te. +aa mea|l|e. a+t+|+.e.
a|.|+am|a M+a+e. a|.| l||e.
Iah|e 11-1 ||se1 :e/|e/ |c|es
320 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
7he sa Login
Thc sa login is thc login ol thc systcm administrator. !n vcrsions prcvious to SQL Scrvcr
2005, in which rolcs did not cxist, thc sa login was grantcd all possiblc pcrmissions lor
systcm administration tasks. Now, thc sa login is includcd just lor backward compatibility.
This login is always a mcmbcr ol thc sysadmin lixcd scrvcr rolc and cannot bc rcmovcd
lrom thc rolc.
|se ||e se |c|s cs|, a|es ||e/e |s sc| csc||e/ ac, |c |c |s |c ||e 1c|c|cse s,s|em.
Assigning a Login to a Iixed Server RoIe
To assign a login to a lixcd scrvcr rolc using SQL Scrvcr Managcmcnt Studio, cxpand
thc scrvcr, cxpand Security, and cxpand Server Roles. Rightclick thc rolc to which
you want to add a login and thcn click Properties. n thc General pagc ol thc Server
Role Properties dialog box (scc Figurc 124), click Add. Scarch lor thc login you want
to add. Such a login is thcn thc mcmbcr ol thc rolc and inhcrits all crcdcntials, which
arc assigncd to that rolc.
||qcre 11-4 :e/|e/ |c|e |/c(e/||es 1|c|c |cs
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 321
Fixed Database RoIes
Fixcd databasc rolcs arc dclincd at thc databasc lcvcl and thcrclorc cxist in cach databasc
bclonging to thc databasc scrvcr. Tablc 122 lists all ol thc lixcd databasc rolcs. Mcmbcrs
ol thc lixcd databasc rolc can pcrlorm dillcrcnt activitics. Usc 8ooks nlinc to lcarn
which activitics arc allowcd lor cach ol thc lixcd databasc rolcs.
8csidcs thc lixcd databasc rolcs listcd in Tablc 122, thcrc is a spccial lixcd databasc
rolc callcd public, which is cxplaincd ncxt.
pubIic RoIe
Thc public rolc is a spccial lixcd databasc rolc to which cvcry lcgitimatc uscr ol a
databasc bclongs. !t capturcs all dclault pcrmissions lor uscrs in a databasc. This
providcs a mcchanism lor giving all uscrs without appropriatc pcrmissions a sct ol
(usually limitcd) pcrmissions. Thc public rolc maintains all dclault pcrmissions lor
uscrs in a databasc and cannot bc droppcd. This rolc cannot havc uscrs, groups, or
rolcs assigncd to it bccausc thcy bclong to thc rolc by dclault. (xamplc 12.19, latcr
in thc chaptcr, shows thc usc ol thc public rolc.)
8y dclault, thc public rolc allows uscrs to do thc lollowing:
\icw systcm tablcs and display inlormation lrom thc master systcm databasc
using ccrtain systcm proccdurcs
xccutc statcmcnts that do not rcquirc pcrmissionslor cxamplc, PR!NT
Iah|e 11-1 ||se1 |c|c|cse |c|es
||xe6 0atahase ke|e 0escr|pt|ea
a|_ewaer J.er. w|e c+a jerlerm +|me.t +|| +ct|.|t|e. |a t|e a+t+|+.e
a|_+cce..+am|a J.er. w|e c+a +aa er reme.e a.er.
a|_a+t+re+aer J.er. w|e c+a .ee a+t+ lrem +|| a.er t+||e. |a t|e a+t+|+.e
a|_a+t+wr|ter J.er. w|e c+a +aa, mea|l, er ae|ete a+t+ |a +|| a.er t+||e. |a t|e a+t+|+.e
a|_aa|+am|a J.er. w|e c+a jerlerm +|| ||| ejer+t|ea. |a t|e a+t+|+.e
a|_.ecar|t+am|a J.er. w|e c+a m+a+e +|| +ct|.|t|e. ceacera|a .ecar|t jerm|..|ea. |a t|e a+t+|+.e
a|_|+c|ajejer+ter J.er. w|e c+a |+c| aj t|e a+t+|+.e
a|_aeaa+t+re+aer J.er. w|e c+aaet .ee +a a+t+ |a t|e a+t+|+.e
a|_aeaa+t+wr|ter J.er. w|e c+aaet c|+ae +a a+t+ |a t|e a+t+|+.e
322 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Assigning a User to a Iixed Database RoIe
To assign a uscr account to a lixcd databasc rolc using SQL Scrvcr Managcmcnt
Studio, cxpand thc scrvcr, cxpand Databases, cxpand thc databasc, cxpand Security,
cxpand Roles, and thcn cxpand Database Roles. Rightclick thc rolc to which you
want to add a uscr and thcn click Properties. !n thc Database Role dialog box, click
Add and browsc lor thc uscr(s) you want to add. Such an account is thcn thc mcmbcr
ol thc rolc and inhcrits all crcdcntials, which arc assigncd to that rolc.
AppIication RoIes
Application rolcs allow you to cnlorcc sccurity lor a particular application. !n othcr
words, application rolcs allow thc application itscll to acccpt thc rcsponsibility ol uscr
authcntication, instcad ol rclying on thc databasc systcm. For instancc, il clcrks in your
company may changc an cmploycc's data only using thc cxisting application (and not
TransactSQL statcmcnts or any othcr tool), you can crcatc an application rolc lor thc
application.
Application rolcs dillcr signilicantly lrom all othcr rolc typcs. First, application rolcs
havc no mcmbcrs, bccausc thcy usc thc application only and thcrclorc do not nccd to grant
pcrmissions dircctly to uscrs. Sccond, you nccd a password to activatc an application rolc.
Vhcn an application rolc is activatcd lor a scssion by thc application, thc scssion
loscs all pcrmissions applicd to thc logins, uscr accounts and groups, or rolcs in all
databascs lor thc duration ol thc scssion. 8ccausc thcsc rolcs arc applicablc only to thc
databasc in which thcy cxist, thc scssion can gain acccss to anothcr databasc only by
virtuc ol pcrmissions grantcd to thc guest uscr account in thc othcr databasc. For this
rcason, il thcrc is no guest uscr account in a databasc, thc scssion cannot gain acccss to
that databasc.
Creating, Modifying, and DeIeting AppIication RoIes
You can crcatc, modily, and dclctc application rolcs using cithcr thc TransactSQL
languagc or systcm proccdurcs. 8ccausc all systcm proccdurcs rclatcd to this topic
(sp_addapprole, sp_setapprole, and sp_dropapprole) arc dcprccatcd lcaturcs and will
bc rcmovcd in onc ol thc lollowing vcrsions ol SQL Scrvcr, this scction discusscs only
thc corrcsponding TransactSQL statcmcnts.
Thc CRAT APPL!CAT!N RL statcmcnt crcatcs an application rolc lor
thc currcnt databasc. This statcmcnt has two options: onc to spccily thc password and
onc to dclinc thc dclault schcmathat is, thc lirst schcma that will bc scarchcd by thc
scrvcr whcn it rcsolvcs thc namcs ol objccts lor this rolc.
xamplc 12.9 adds a ncw application rolc callcd weekly_reports to thc sample databasc.
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 323
XAMPL 12.9
US samplc,
CRAT APPL!CAT!N RL wcckly_rcports
V!TH PASSVR -'x1y2z3w4',
FAULT_SCHMA -my_schcma,
You can modily and rcmovc application rolcs using thc ALTR APPL!CAT!N
RL and RP APPL!CAT!N RL statcmcnts, rcspcctivcly.
Thc ALTR APPL!CAT!N RL statcmcnt changcs thc namc, password, or
dclault schcma ol an cxisting application rolc. Thc syntax ol this statcmcnt is similar to
thc syntax ol thc CRAT APPL!CAT!N RL statcmcnt. To cxccutc thc ALTR
APPL!CAT!N RL statcmcnt, you nccd thc ALTR pcrmission on thc rolc.
Thc RP APPL!CAT!N RL statcmcnt rcmovcs thc application rolc lrom thc
currcnt databasc. !l thc application rolc owns any objccts (sccurablcs), it cannot bc droppcd.
Activating AppIication RoIes
Altcr a conncction is startcd, it must cxccutc thc sp_setapprole systcm proccdurc to
activatc thc pcrmissions that arc associatcd with an application rolc. This proccdurc has
thc lollowing syntax:
sp_sctapprolc |Crolcnamc -| 'rolc' ,
|Cpassword -| 'password'
|,|Ccncrypt -| 'cncrypt_stylc'|
role is thc namc ol thc application rolc dclincd in thc currcnt databasc, password
spccilics thc corrcsponding password, and encrypt_style dclincs thc cncryption stylc
spccilicd lor thc password.
Vhcn you activatc an application rolc using sp_setapprole, you nccd to know thc
lollowing:
Altcr thc activation ol an application rolc, you cannot dcactivatc it in thc currcnt
databasc until thc scssion is disconncctcd lrom thc systcm.
An application rolc is always databasc boundthat is, its scopc is thc currcnt
databasc. !l you changc thc currcnt databasc within a scssion, you arc allowcd to
pcrlorm othcr activitics bascd on thc pcrmissions in that databasc.
|e 1es|s c/ c((||:c||cs /c|es |s :9| :e/|e/ 1^^? |s sa|c(||mc|, |e:case || |s sc| as|/c/m. c :/ec|e cs1
1e|e|e c((||:c||cs /c|es, ,ca ase /cssc:|-:9|. //|e/ ||c|, ||e c:|||c||cs c/ c((||:c||cs /c|es |s 1cse |, c
s,s|em (/c:e1a/e.
324 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Managing AppIication RoIes Using Management Studio
To crcatc an application rolc using SQL Scrvcr Managcmcnt Studio, cxpand thc scrvcr,
cxpand Databases, and thcn cxpand thc databasc and its Security loldcr. Rightclick
Roles, click New, and thcn click New Application Role. !n thc Application Role
dialog box, cntcr thc namc ol thc ncw rolc. Additionally, you must cntcr thc password
and may cntcr thc dclault schcma lor thc ncw rolc.
Gcncrally, uscrdclincd databasc rolcs arc applicd whcn a group ol databasc uscrs nccds
to pcrlorm a common sct ol activitics within a databasc and no applicablc Vindows
group cxists. Thcsc rolcs arc crcatcd (dclctcd) using cithcr TransactSQL statcmcnts
or systcm proccdurcs. This scction discusscs only TransactSQL statcmcnts, bccausc
systcm proccdurcs conccrning uscrdclincd rolcs (sp_addrole and sp_droprole) arc
a dcprccatcd lcaturc.
Creating and DeIeting User-Defined RoIes
Thc CRAT RL statcmcnt crcatcs a ncw uscrdclincd databasc rolc in thc currcnt
databasc. Thc syntax ol this statcmcnt is
CRAT RL rolc_namc |AUTHR!ZAT!N owncr_namc|
role_name is thc namc ol thc uscrdclincd rolc to bc crcatcd. owner_name spccilics
thc databasc uscr or rolc that will own thc ncw rolc. (!l no uscr is spccilicd, thc rolc will
bc owncd by thc uscr that cxccutcs thc CRAT RL statcmcnt.)
Thc ALTR RL statcmcnt changcs thc namc ol a uscrdclincd databasc rolc.
Similarly, thc RP RL statcmcnt drops a rolc lrom thc databasc. Rolcs that own
databasc objccts (sccurablcs) cannot bc droppcd lrom thc databasc. To drop such a rolc,
you must lirst translcr thc owncrship ol thosc objccts.
RoIes and System Procedures
Thcrc arc still scvcral systcm proccdurcs that you havc to usc il you nccd to add or
rcmovc mcmbcrs ol a uscrdclincd rolc:
sp_addrolcmcmbcr
sp_droprolcmcmbcr
sp_hclprolc
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 325
Altcr you add a rolc to thc currcnt databasc, you can usc thc systcm proccdurc
sp_addrolemember to add mcmbcrs to thc rolc. A rolc mcmbcr can bc any valid login,
Vindows uscr account or group, or anothcr rolc. nly mcmbcrs ol thc db_owner
databasc rolc can cxccutc this systcm proccdurc. Additionally, rolc owncrs can cxccutc
sp_addrolemember to add a mcmbcr to any rolc that thcy own.
Thc sp_droprolemember systcm proccdurc rcmovcs an cxisting mcmbcr lrom
thc rolc. (!t is not possiblc to usc this systcm proccdurc to rcmovc an cxisting
Vindows uscr account lrom a Vindows group.) nly mcmbcrs ol thc db_owner
or db_securityadmin databasc rolcs can cxccutc this systcm proccdurc.
Thc sp_helprole systcm proccdurc displays inlormation (rolc ! and namc) about a
particular rolc, or all rolcs in thc currcnt databasc il no rolc namc is providcd. nly thc
mcmbcrs ol thc db_owner or db_securityadmin rolcs can cxccutc this systcm proccdurc.
/c|s, ||e 1es|s c/ /c|es (|s |||s :cse, ase/-1e/|se1 1c|c|cse /c|es |s :9| :e/|e/ 1^^? |s se|||e/ as|/c/m sc/
c(||mc|. c :/ec|e cs1 1e|e|e ase/-1e/|se1 /c|es, ,ca ase /cssc:|-:9|, a|e/ecs |c c11 sa:| /c|es |c ||e :a//es|
1c|c|cse, ,ca ase s,s|em (/c:e1a/es.
xamplc 12.10 shows how you can crcatc and add mcmbcrs to a uscrdclincd rolc.
XAMPL 12.10
US samplc,
CRAT RL markcting AUTHR!ZAT!N pctcr,
G
cxcc sp_addrolcmcmbcr Crolcnamc - 'markcting', Cmcmbcrnamc - 'pctcr',
cxcc sp_addrolcmcmbcr Crolcnamc - 'markcting', Cmcmbcrnamc - 'mary',
xamplc 12.10 lirst crcatcs thc uscrdclincd rolc callcd marketing, and thcn, using thc
sp_addrolemember systcm proccdurc, adds two mcmbcrs, peter and mary, to thc rolc.
Managing User-Defined RoIes Using Management Studio
To crcatc a uscrdclincd rolc using SQL Scrvcr Managcmcnt Studio, cxpand thc scrvcr,
cxpand Databases, and thcn cxpand thc databasc and its Security loldcr. Rightclick
Roles, click New, and thcn click New Database Role. !n thc Database Role dialog box
(scc Figurc 125), cntcr thc namc ol thc ncw rolc. Click Add to add mcmbcrs to thc
ncw rolc. Choosc thc mcmbcrs (uscrs and/or othcr rolcs) ol thc ncw rolc and click OK.
326 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Autborization
nly authorizcd uscrs arc ablc to cxccutc statcmcnts or pcrlorm opcrations on an cntity.
!l an unauthorizcd uscr attcmpts to do cithcr task, thc cxccution ol thc TransactSQL
statcmcnt or thc opcration on thc databasc objcct will bc rcjcctcd.
Thcrc arc thrcc TransactSQL statcmcnts rclatcd to authorization:
GRANT
NY
R\K
8clorc you rcad about thcsc thrcc statcmcnts, you nccd to bc awarc ol onc ol thc
most important sccurity propcrtics ol atabasc nginc: it supports multiplc scopcs
and pcrmissions to hclp databasc administrators handlc pcrmissions. Thc authorization
modcl scparatcs thc world into principals and sccurablc. vcry sccurablc has associatcd
||qcre 11- |c|c|cse |c|e 1|c|c |cs
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 327
pcrmissions that can bc grantcd to a principal. Principals, such as individuals, groups,
or applications, can acccss cntitics. ntitics arc thc rcsourccs to which thc authorization
subsystcm rcgulatcs acccss. As prcviously statcd, thcrc arc thrcc sccurablc scopcs: scrvcr,
databasc, and schcma, which contain othcr sccurablcs, such as login, databasc uscrs, tablcs,
and storcd proccdurcs.
CRAN7 Statement
Thc GRANT statcmcnt grants pcrmissions to sccurablcs. Thc syntax ol thc GRANT
statcmcnt is
GRANT [ALL |PR!\!LGS|] ] pcrmission_list
|N |class::| sccurablc| T principal_list |V!TH GRANT PT!N|
|AS principal |
Thc ALL clausc indicatcs that all pcrmissions applicablc to thc spccilicd sccurablc
will bc grantcd to thc spccilicd principal. (For thc list ol spccilic sccurablcs, scc 8ooks
nlinc.) permission_list spccilics cithcr statcmcnts or objccts (scparatcd by commas) lor
which thc pcrmissions arc grantcd. class spccilics cithcr a sccurablc class or a sccurablc
namc lor which pcrmission will bc grantcd. N securable spccilics thc sccurablc lor
which pcrmissions arc grantcd (scc xamplc 12.15 latcr in this scction). principal_list
lists all accounts (scparatcd by commas) to which pcrmissions arc grantcd. principal and
thc componcnts ol principal_list can bc a Vindows uscr account, a login or uscr account
mappcd to a ccrtilicatc, a login mappcd to an asymmctric kcy, a databasc uscr, a databasc
rolc, or an application rolc.
Tablc 123 lists and dcscribcs all thc pcrmissions and lists thc corrcsponding sccurablcs
to which thcy apply.
c||e !1-? s|cas cs|, ||e mcs| |m(c/|cs| (e/m|ss|css. |e se:a/||, mc1e| c/ |c|c|cse |s|se |s ||e/c/:||:c|.
|es:e, ||e/e c/e mcs, /csa|c/ (e/m|ss|css ||c| c/e sc| ||s|e1 |s ||e |c||e. ca :cs /|s1 ||e 1es:/|(||cs c/ ||ese
(e/m|ss|css |s 3cc|s 0s||se.
Thc lollowing cxamplcs dcmonstratc thc usc ol thc GRANT statcmcnt. To bcgin,
xamplc 12.11 dcmonstratcs thc usc ol thc CRAT pcrmission.
XAMPL 12.11
US samplc,
GRANT CRAT TA8L, CRAT PRCUR
T pctcr, mary,
328 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Iah|e 11-1 |e/m|ss|css a||| tc//es(cs1|s :e:a/c||es
|erm|ss|ea kpp||es Ie 0escr|pt|ea
:|||CI I+||e. + ce|ama., .aeam., .|ew. +
ce|ama., t+||e-.+|aea laact|ea.
|re.|ae. t|e +||||t te .e|ect (re+a} rew.. \ea c+a
re.tr|ct t||. jerm|..|ea te eae er mere ce|ama. |
||.t|a t|em. (|l t|e ||.t |. em|ttea, +|| ce|ama. el t|e
t+||e c+a |e .e|ectea.}
|N:||I I+||e. + ce|ama., .aeam., .|ew. + ce|ama. |re.|ae. t|e +||||t te |a.ert rew..
J|||I| I+||e. + ce|ama., .aeam., .|ew. + ce|ama. |re.|ae. t|e +||||t te mea|l ce|ama .+|ae.. \ea c+a
re.tr|ct t||. jerm|..|ea te eae er mere ce|ama. |
||.t|a t|em. (|l t|e ||.t |. em|ttea, +|| ce|ama. el t|e
t+||e c+a |e mea|l|ea.}
||||I| I+||e. + ce|ama., .aeam., .|ew. + ce|ama. |re.|ae. t|e +||||t te ae|ete rew..
||||||NC|: J.er-ael|aea laact|ea. (:9| +aa C||}, t+||e. +
ce|ama., .aeam., .|ew. + ce|ama.
|re.|ae. t|e +||||t te relereace ce|ama. el t|e
lere|a |e |a t|e relereacea t+||e w|ea t|e a.er |+.
ae :|||CI jerm|..|ea ler t|e relereacea t+||e.
|/|CJI| :terea jreceaare. (:9| +aa C||}, a.er-ael|aea
laact|ea. (:9| +aa C||}, .aeam.
|re.|ae. t|e +||||t te e\ecate t|e .jec|l|ea .terea
jreceaare er a.er-ael|aea laact|ea..
C0NI|0| :terea jreceaare. (:9| +aa C||}, a.er-ael|aea
laact|ea. (:9| +aa C||}, .aeam.
|re.|ae. ewaer.||j-|||e c+j+||||t|e., t|e r+atee
ellect|.e| |+. +|| ael|aea jerm|..|ea. ea t|e
.ecar+||e. | jr|ac|j+| t|+t |+. |eea r+atea C0NI|0|
+|.e |+. t|e +||||t te r+at jerm|..|ea. ea t|e
.ecar+||e. C0NI|0| +t + j+rt|ca|+r .ceje |mj||c|t|
|ac|aae. C0NI|0| ea +|| t|e .ecar+||e. aaaer t|+t
.ceje (.ee |\+mj|e z.}.
||I|| :terea jreceaare. (:9| +aa C||}, a.er-ael|aea
laact|ea. (:9| +aa C||}, t+||e., .|ew.
|re.|ae. t|e +||||t te +|ter t|e jrejert|e. (e\cejt
ewaer.||j} el + j+rt|ca|+r .ecar+||e. \|ea r+atea ea
+ .ceje, |t +|.e |e.tew. t|e +||||t te ||I||, C|||I|,
er ||0| +a .ecar+||e ceat+|aea w|t||a t|+t .ceje.
I||| 0\N||:||| :terea jreceaare. (:9| +aa C||}, a.er-ael|aea
laact|ea. (:9| +aa C||}, t+||e., .|ew., .aeam.
|re.|ae. t|e +||||t te t+|e ewaer.||j el t|e
.ecar+||e ea w||c| |t |. r+atea.
\||\ ||||N|I|0N :terea jreceaare. (:9| +aa C||}, a.er-ael|aea
laact|ea. (:9| +aa C||}, t+||e., .|ew., .aeam.
Ceatre|. t|e +||||t el t|e r+atee te .ee t|e
met+a+t+ el t|e .ecar+||e (.ee |\+mj|e z.!}.
C|||I| (:er.er
.ecar+||e}
a/+ |re.|ae. t|e +||||t te cre+te t|e .er.er .ecar+||e.
C|||I| (||
.ecar+||e}
a/+ |re.|ae. t|e +||||t te cre+te t|e a+t+|+.e .ecar+||e.
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 329
!n xamplc 12.11, thc uscrs peter and mary can cxccutc thc TransactSQL statcmcnts
CRAT TA8L and CRAT PRCUR. (As you can scc lrom this cxamplc,
thc GRANT statcmcnt with thc CRAT pcrmission docs not includc thc N option.)
xamplc 12.12 allows thc uscr mary to crcatc uscrdclincd lunctions in thc sample
databasc.
XAMPL 12.12
US samplc,
GRANT CRAT FUNCT!N T mary,
xamplc 12.13 shows thc usc ol thc SLCT pcrmission within thc GRANT
statcmcnt.
XAMPL 12.13
US samplc,
GRANT SLCT N cmploycc
T pctcr, mary,
!n xamplc 12.13, thc uscrs peter and mary can rcad rows lrom thc employee tablc.
|es c (e/m|ss|cs |s /cs|e1 |c c |s1cas ase/ c::cas| c/ c |c|s, |||s c::cas| (|c|s |s ||e cs|, cse c//e:|e1
|, ||e (e/m|ss|cs. 0s ||e c||e/ |cs1, |/ c (e/m|ss|cs |s /cs|e1 |c c /ca( c/ /c|e, ||e (e/m|ss|cs c//e:|s c||
ase/s |e|cs|s |c ||e /ca( (/c|e.
xamplc 12.14 shows thc usc ol thc UPAT pcrmission within thc GRANT
statcmcnt.
XAMPL 12.14
US samplc,
GRANT UPAT N works_on (cmp_no, cntcr_datc) T pctcr,
!n xamplc 12.14, thc uscr peter can modily two columns ol thc works_on tablc:
emp_no and enter_date.
xamplc 12.15 shows thc usc ol thc \!V F!N!T!N pcrmission.
XAMPL 12.15
US samplc,
GRANT \!V F!N!T!N N 8JCT::cmploycc T pctcr,
GRANT \!V F!N!T!N N SCHMA::dbo T pctcr,
330 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
xamplc 12.15 shows two GRANT statcmcnts lor thc \!V F!N!T!N
pcrmission. Thc lirst onc allows thc uscr peter to scc mctadata about thc employee
tablc ol thc sample databasc. (8JCT is onc ol thc basc sccurablcs, and you can
usc this clausc to givc pcrmissions lor spccilic objccts, such as tablcs, vicws, and storcd
proccdurcs.) 8ccausc ol thc hicrarchical structurc ol sccurablcs, you can usc a "highcr"
sccurablc to cxtcnd thc \!V F!N!T!N (or any othcr basc) pcrmission. Thc
sccond statcmcnt in xamplc 12.15 givcs thc uscr peter acccss to mctadata ol all thc
objccts ol thc dbo schcma ol thc sample databasc.
|s |e/s|css (/e||cas |c :9| :e/|e/ 1^^:, || |s (css|||e |c ae/, |s/c/mc||cs cs c|| 1c|c|cse c|(e:|s, e|es |/ ||ese
c|(e:|s c/e case1 |, csc||e/ ase/. |e l|| |||||||0| (e/m|ss|cs sca c||cas ,ca |c /cs| c/ 1es, c::ess |c
1|//e/es| (|e:es c/ ,ca/ me|c1c|c cs1 |es:e |c 1e:|1e a||:| (c/| c/ me|c1c|c |s ||s|||e |c c||e/ ase/s.
xamplc 12.16 shows thc usc ol thc CNTRL pcrmission.
XAMPL 12.16
US samplc,
GRANT CNTRL N ATA8AS::samplc T pctcr,
!n xamplc 12.16, thc uscr peter cllcctivcly has all dclincd pcrmissions on thc
sccurablc (in this casc, thc sample databasc). A principal that has bccn grantcd
CNTRL also implicitly has thc ability to grant pcrmissions on thc sccurablc, in
othcr words, thc CNTRL pcrmission includcs thc V!TH GRANT PT!N
clausc (scc xamplc 12.17). Thc CNTRL pcrmission is thc highcst pcrmission in
rclation to scvcral basc sccurablcs. For this rcason, CNTRL at a particular scopc
implicitly includcs CNTRL on all thc sccurablcs undcr that scopc. Thcrclorc, thc
CNTRL pcrmission ol pctcr on thc sample databasc implics all pcrmissions on this
databasc, all pcrmissions on all asscmblics in thc databasc, all pcrmissions on all schcmas
in thc sample databasc, and all pcrmissions on objccts within thc sample databasc.
8y dclault, il uscr A grants a pcrmission to uscr 8, thcn uscr 8 can only usc thc
pcrmission to cxccutc thc TransactSQL statcmcnt listcd in thc GRANT statcmcnt.
Thc V!TH GRANT PT!N givcs uscr 8 thc additional capability ol granting thc
privilcgc to othcr uscrs, as shown in xamplc 12.17.
XAMPL 12.17
US samplc,
GRANT SLCT N works_on T mary
V!TH GRANT PT!N,
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 331
!n xamplc 12.17, thc uscr mary can usc thc SLCT statcmcnt to rctricvc rows
lrom thc works_on tablc and also may grant this privilcgc to othcr uscrs ol thc sample
databasc.
DNY Statement
Thc NY statcmcnt prcvcnts uscrs lrom pcrlorming actions. This mcans that thc
statcmcnt rcmovcs cxisting pcrmissions lrom uscr accounts or prcvcnts uscrs lrom
gaining pcrmissions through thcir group/rolc mcmbcrship that might bc grantcd in thc
luturc. This statcmcnt has thc lollowing syntax:
NY [ALL |PR!\!LGS| ] ] pcrmission_list
|N |class::| sccurablc| T principal_list
|CASCA| | AS principal |
All options ol thc NY statcmcnt havc thc samc logical mcaning as thc options
with thc samc namc in thc GRANT statcmcnt. NY has an additional option,
CASCA, which spccilics that pcrmissions will bc dcnicd to uscr A and any othcr
uscrs to whom uscr A passcd this pcrmission. (!l thc CASCA option is not spccilicd
in thc NY statcmcnt, and thc corrcsponding objcct pcrmission was grantcd with thc
V!TH GRANT PT!N, an crror is rcturncd.)
Thc NY statcmcnt prcvcnts thc uscr, group, or rolc lrom gaining acccss to thc
pcrmission grantcd through thcir group or rolc mcmbcrship. This mcans that il a uscr
bclongs to a group (or rolc) and thc grantcd pcrmission lor thc group is dcnicd to thc
uscr, this uscr will bc thc only onc ol thc group who cannot usc this pcrmission. n thc
othcr hand, il a pcrmission is dcnicd lor a wholc group, all mcmbcrs ol thc group will
bc dcnicd thc pcrmission.
ca :cs |||s| c/ ||e |/| s|c|emes| cs c (cs||||e cs1 ||e ||| s|c|emes| cs c sec|||e ase/
ca||c/|cc||cs. |sac||,, ||e ||| s|c|emes| |s ase1 |c 1es, c|/ec1, es|s||s (e/m|ss|css /c/ /ca(s (/c|es
|c c /ea mem|e/s c/ ||e /ca(.
xamplcs 12.18 and 12.19 show thc usc ol thc NY statcmcnt.
XAMPL 12.18
US samplc,
NY CRAT TA8L, CRAT PRCUR
T pctcr,
332 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Thc NY statcmcnt in xamplc 12.18 dcnics two prcviously grantcd statcmcnt
pcrmissions to thc uscr peter.
XAMPL 12.19
US samplc,
GRANT SLCT N projcct
T PU8L!C,
NY SLCT N projcct
T pctcr, mary,
xamplc 12.19 shows thc ncgativc authorization ol somc uscrs ol thc sample
databasc. First, thc rctricval ol all rows ol thc project tablc is grantcd to all uscrs ol thc
sample databasc. Altcr that, this pcrmission is dcnicd to two uscrs: peter and mary.
RVDk Statement
Thc R\K statcmcnt rcmovcs onc or morc prcviously grantcd or dcnicd pcrmissions.
This statcmcnt has thc lollowing syntax:
R\K |GRANT PT!N FR|
[ |ALL |PR!\!LGS| | ] pcrmission_list |]
|N |class:: | sccurablc |
FRM principal_list |CASCA| | AS principal |
Thc only ncw option in thc R\K statcmcnt is GRANT PT!N FR. (All
othcr options havc thc samc logical mcaning as thc options with thc samc namcs in thc
GRANT or NY statcmcnt.) GRANT PT!N FR is uscd to rcmovc thc cllccts
ol thc V!TH GRANT PT!N in thc corrcsponding GRANT statcmcnt. This
mcans that thc uscr will still havc thc prcviously grantcd pcrmissions but will no longcr
bc ablc to grant thc pcrmission to othcr uscrs.
|e ||l0|| s|c|emes| /e|c|es (cs||||e (e/m|ss|css s(e:|/|e1 a||| ||e |/| s|c|emes| cs ae|| cs sec|||e
(e/m|ss|css ese/c|e1 |, ||e ||| s|c|emes|. |e/e/c/e, ||s /as:||cs |s |c sea|/c||ce ||e s(e:|/|e1 ((cs||||e c/
sec|||e (e/m|ss|css.
xamplc 12.20 shows thc usc ol thc R\K statcmcnt.
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 333
XAMPL 12.20
US samplc,
R\K SLCT N projcct
FRM PU8L!C,
Thc R\K statcmcnt in xamplc 12.20 rcvokcs thc grantcd pcrmission lor thc
public rolc. At thc samc timc, thc cxisting "ncgativc" pcrmissions lor thc uscrs peter
and mary arc not rcvokcd (as in xamplc 12.19), bccausc thc cxplicitly grantcd or
dcnicd pcrmissions arc not allcctcd by rcvoking rolcs or groups.
Managing Permissions Using Management Studio
atabasc uscrs can pcrlorm activitics that arc grantcd to thcm. !n this casc, thcrc is a
corrcsponding cntry in thc sys.database_permissions catalog vicw (that is, thc valuc
ol thc state column is sct to G lor grant). A ncgativc cntry in thc tablc prcvcnts a
uscr lrom pcrlorming activitics. Thc cntry D (dcny) in thc state column ovcrridcs a
pcrmission that was grantcd to a uscr cxplicitly or implicitly using a rolc to which thc
uscr bclongs. Thcrclorc, thc uscr cannot pcrlorm this activity in any casc. !n thc last
casc (valuc R), thc uscr has no cxplicit privilcgcs but can pcrlorm an activity il a rolc to
which thc uscr bclongs has thc appropriatc pcrmission.
To managc pcrmissions lor a uscr or rolc using Managcmcnt Studio, cxpand thc
scrvcr and cxpand Databases. Rightclick thc databasc and click Properties. Choosc
thc Permissions pagc and click thc Add button. !n thc atabasc Propcrtics dialog
box, shown in Figurc 126, you can sclcct onc or morc objcct typcs (uscrs and/or rolcs)
to which you want to grant or dcny pcrmissions. To grant a pcrmission, chcck thc
corrcsponding box in thc Grant column and click OK. To dcny a pcrmission, chcck
thc corrcsponding box in thc Deny column. (Thc With Grant column spccilics that
thc uscr has thc additional capability ol granting thc privilcgc to othcr uscrs.) 8lanks in
thcsc columns mcan no pcrmission.
To managc pcrmissions lor a singlc databasc objcct using SQL Scrvcr Managcmcnt
Studio, cxpand thc scrvcr, cxpand Databases, cxpand thc databasc, and thcn cxpand
Tables, Views, or Synonyms, dcpcnding on thc databasc objcct lor which you want
to managc pcrmissions. Rightclick thc objcct, choosc Properties, and sclcct thc
Permissions pagc. (Figurc 127 shows thc Table Properties dialog box lor thc employee
tablc.) Click thc Add button to opcn thc Select Users or Roles dialog box. Click Object
Types and sclcct onc or morc objcct typcs (uscrs, databasc rolcs, application rolcs). Altcr
that, click Browse and chcck all objccts to which pcrmissions should bc grantcd. To grant
a pcrmission, chcck thc corrcsponding box in thc Grant column. To dcny a pcrmission,
chcck thc corrcsponding box in thc Deny column.
334 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
7racking Cbanges
Tracking changes rclcrs to documcnting all inscrt, updatc, and dclctc activitics that arc
applicd to tablcs ol thc databasc. Thc trackcd changcs can thcn bc vicwcd to lind out
who acccsscd thc data and whcn thcy acccsscd it. Thcrc arc two ways in which you can
track changcs:
Using triggcrs
Using changc data capturc (CC)
||qcre 11-6 /csc|s s|c|emes| (e/m|ss|css as|s :9| :e/|e/ /cscemes| :|a1|c
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 335
You can usc triggcrs to crcatc an audit trail ol activitics in onc or morc tablcs ol
thc databasc. Thc scction "Altcr Triggcrs" in Chaptcr 14 and xamplc 14.1 show how
triggcrs can bc uscd to track such changcs. Thcrclorc, thc locus ol this scction is CC.
CC is a tracking mcchanism that you can usc to scc changcs as thcy happcn. Thc
primary goal ol CC is to audit who changcd what data and whcn, but it can also bc
uscd to support concurrcncy updatcs. (!l an application wants to modily a row, CC
can chcck thc changc tracking inlormation to makc surc that thc row hasn't bccn
changcd sincc thc last timc thc application modilicd thc row. This chcck is callcd
a "concurrcncy updatc".)
t|t |s c|c||c||e cs|, |s ||e :9| :e/|e/ 1^^? |s|e/(/|se cs1 |e|e|c(e/ e1|||css.
||qcre 11-I /csc|s c|(e:| (e/m|ss|css as|s :9| :e/|e/ /cscemes| :|a1|c
336 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
8clorc a capturc instancc can bc crcatcd lor individual tablcs, thc databasc that
contains thc tablcs must bc cnablcd lor CC, which you do with thc systcm storcd
proccdurc sys.sp_cdc_enable_db as shown in xamplc 12.21. (nly mcmbcrs ol thc
sysadmin lixcd scrvcr rolc can cxccutc this proccdurc.)
XAMPL 12.21
US samplc,
XCUT sys.sp_cdc_cnablc_db
To dctcrminc whcthcr thc sample databasc is cnablcd lor CC, you can rctricvc
thc valuc ol thc column is_cdc_enabled in thc sys.databases catalog vicw. Thc valuc 1
indicatcs thc activation ol CC lor thc particular databasc.
Vhcn a databasc is cnablcd lor CC, thc cdc schcma, cdc uscr, mctadata tablcs, and
othcr systcm objccts arc crcatcd lor thc databasc. Thc cdc schcma contains thc CC
mctadata tablcs as wcll as thc individual tracking tablcs that scrvc as a rcpository lor CC.
ncc a databasc has bccn cnablcd lor CC, you can crcatc a targct tablc that will
capturc changcs lor a particular sourcc tablc. You cnablc thc tablc by using thc storcd
proccdurc sys.sp_cdc_enable_table. (nly mcmbcrs ol thc db_owner lixcd databasc
rolc can cxccutc this proccdurc.) xamplc 12.22 shows thc usc ol this systcm storcd
proccdurc.
|e :9|:e/|e//es| se/||:e mas| |e /ass|s |e/c/e ,ca esc||e |c||es /c/ t|t.
XAMPL 12.22
US samplc,
XCUT sys.sp_cdc_cnablc_tablc
Csourcc_schcma - N'dbo', Csourcc_namc - N'works_on',
Crolc_namc - N'cdc_admin',
Thc sys.sp_cdc_enable_table_change_data_capture systcm proccdurc in xamplc
12.22 cnablcs CC lor thc spccilicd sourcc tablc in thc currcnt databasc. Vhcn a
tablc is cnablcd lor CC, all ML statcmcnts arc rcad lrom thc transaction log and
capturcd in thc associatcd changc tablc. Thc source_schema paramctcr spccilics thc
namc ol thc schcma in which thc sourcc tablc bclongs. source_name is thc namc ol
thc sourcc tablc on which you cnablc CC. Thc role_name paramctcr spccilics thc
namc ol thc databasc rolc uscd to allow acccss to data.
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 337
Crcating a capturc instancc also crcatcs a tracking tablc that corrcsponds to thc sourcc
tablc. You can spccily up to two capturc instanccs lor a sourcc tablc. xamplc 12.23 changcs
thc contcnt ol thc sourcc tablc (works_on).
XAMPL 12.23
US samplc,
!NSRT !NT works_on \ALUS (10102, 'p2', 'Analyst', NULL),
!NSRT !NT works_on \ALUS (9031, 'p2', 'Analyst', NULL),
!NSRT !NT works_on \ALUS (29346, 'p3', 'Clcrk', NULL),
8y dclault, at lcast onc tablcvalucd lunction is crcatcd to acccss thc data in thc
associatcd changc tablc. This lunction allows you to qucry all changcs that occur within
a dclincd intcrval. Thc lunction namc is thc concatcnation ol cdc.ln_cdc_gct_all_
changcs_ and thc valuc assigncd to thc capture_instance paramctcr. !n this casc, thc
paramctcr has thc valuc dbo_works_on, as xamplc 12.24 shows.
XAMPL 12.24
US samplc,
SLCT
FRM cdc.ln_cdc_gct_all_changcs_dbo_works_on
(sys.ln_cdc_gct_min_lsn('dbo_works_on'), sys.ln_cdc_gct_max_lsn(), 'all'),
Thc rcsult is
__;start_|sa __;cp6ate_mask emp_ae pre[ect_ae [eh eater_6ate
\C||1 \| z jz |a+|.t NJ||
\|1 \| 1 jz |a+|.t NJ||
\|1 \| z1+ j1 C|er| NJ||
xamplc 12.24 shows all changcs that happcncd altcr thc cxccution ol thc thrcc
!NSRT statcmcnts. !l you want to track all changcs in a ccrtain timc intcrval, you can
usc a batch similar to thc onc shown in xamplc 12.25.
XAMPL 12.25
US samplc,
CLAR Clrom_lsn binary(10), Cto_lsn binary(10),
SLCT Clrom_lsn -
sys.ln_cdc_map_timc_to_lsn('smallcst grcatcr than', GTAT() 1),
338 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
SLCT Cto_lsn -
sys.ln_cdc_map_timc_to_lsn('largcst lcss than or cqual', GTAT()),
SLCT FRM
cdc.ln_cdc_gct_all_changcs_dbo_works_on (Clrom_lsn, Cto_lsn, 'all'),
Thc only dillcrcncc bctwccn xamplc 12.25 and xamplc 12.24 is that xamplc 12.25
uscs two paramctcrs (from_lsn and to_lsn) to dclinc thc bcginning and cnd ol thc
timc intcrval. (Thc assignmcnt ol timc boundarics is donc using thc sys.fn_cdc_map_
time_to_lsn() lunction.)
Data Security and Views
As alrcady statcd in Chaptcr 11, vicws can bc uscd lor thc lollowing purposcs:
To rcstrict thc usc ol particular columns and/or rows ol tablcs
To hidc thc dctails ol complicatcd qucrics
To rcstrict inscrtcd and updatcd valucs to ccrtain rangcs
Rcstricting thc usc ol particular columns and/or rows mcans that thc vicw mcchanism
providcs itscll with thc control ol data acccss. For cxamplc, il thc employee tablc also
contains thc salarics ol cach cmploycc, thcn acccss to thcsc salarics can bc rcstrictcd using
a vicw that acccsscs all columns ol thc tablc cxccpt thc salary column. Subscqucntly,
rctricval ol data lrom thc tablc can bc grantcd to all uscrs ol thc databasc using thc vicw,
whilc only a small numbcr ol (privilcgcd) uscrs will havc thc samc pcrmission lor all data
ol thc tablc.
Thc lollowing thrcc cxamplcs show thc usc ol vicws to rcstrict thc acccss to data.
XAMPL 12.26
US samplc,
G
CRAT \!V v_without_budgct
AS SLCT projcct_no, projcct_namc
FRM projcct,
Using thc v_without_budget vicw, it is possiblc to dividc uscrs into two groups: thc
group ol privilcgcd uscrs who can acccss thc budgct ol all projccts, and thc group ol
common uscrs who can acccss all rows lrom thc projects tablc but not thc data lrom
thc budget column.
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 339
XAMPL 12.27
US samplc,
G
ALTR TA8L cmploycc
A uscr_namc CHAR(60) FAULT SYSTM_USR,
G
CRAT \!V v_my_rows
AS SLCT cmp_no, cmp_lnamc, cmp_lnamc, dcpt_no
FRM cmploycc
VHR uscr_namc - SYSTM_USR,
|e /cssc:|-:9| s|c|emes|s |s |scm(|e !1.1/ mas| |e se(c/c|e|, ese:a|e1, |e:case ||e t||/| l||
s|c|emes| mas| |e ||e /|/s| s|c|emes| |s ||e |c|:|. |c| |s a|, ||e 0 s|c|emes| |s ase1 (|c mc/| ||e es1
c/ ||e /|/s| |c|:|.
Thc schcma ol thc employee tablc is modilicd in xamplc 12.27 by adding thc ncw
column user_name. vcry timc a ncw row is inscrtcd into thc employee tablc, thc
systcm login is inscrtcd into thc user_name column. Altcr thc crcation ol corrcsponding
vicws, cvcry uscr can rctricvc only thc rows that thcy inscrtcd into thc tablc. (Thc samc is
truc lor thc UPAT statcmcnt.)
XAMPL 12.28
US samplc,
G
CRAT \!V v_analyst
AS SLCT cmploycc.cmp_no, cmp_lnamc, cmp_lnamc
FRM cmploycc, works_on
VHR cmploycc.cmp_no - works_on.cmp_no
AN job - 'Analyst',
Thc v_analyst vicw rcprcscnts a horizontal and a vcrtical subsct (in othcr words, it
limits thc rows and columns that can bc acccsscd) ol thc employee tablc.
ConcIusion
Thc lollowing arc thc most important conccpts ol databasc systcm sccurity:
Authcntication
ncryption
340 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Authorization
Tracking changcs
Authcntication is thc proccss ol validating uscr crcdcntials to prcvcnt unauthorizcd
uscrs lrom using a systcm. !t is most commonly cnlorccd by rcquiring a uscrnamc
and password. ata cncryption is thc proccss ol scrambling inlormation so that it
is incomprchcnsiblc until it is dccryptcd by thc intcndcd rccipicnt. Scvcral dillcrcnt
mcthods can bc uscd to cncrypt data.
uring thc authorization proccss, thc systcm dctcrmincs what rcsourccs thc particular
uscr can usc. atabasc nginc supports authorization with thc lollowing TransactSQL
statcmcnts: GRANT, NY, and R\K. Tracking changcs mcans that actions ol
unauthorizcd uscrs arc lollowcd and documcntcd on your systcm. This proccss is usclul
to protcct thc systcm against uscrs with clcvatcd privilcgcs.
Thc ncxt chaptcr discusscs thc lcaturcs conccrning atabasc nginc as a multiuscr
soltwarc systcm and dcscribcs thc notions ol optimistic and pcssimistic concurrcncy.
xercises
.12.1
Vhat is a dillcrcncc bctwccn Vindows modc and Mixcd modc:
.12.2
Vhat is a dillcrcncc bctwccn a SQL Scrvcr login and a databasc uscr account:
.12.3
Crcatc thrcc logins callcd ann, burt, and chuck. Thc corrcsponding passwords arc
a1b2c3d4e5, d4e3f2g1h0, and f102gh285, rcspcctivcly. Thc dclault databasc is thc
sample databasc. Altcr crcating thc logins, chcck thcir cxistcncc using thc systcm catalog.
.12.4
Crcatc thrcc ncw databasc uscrnamcs lor thc logins in .12.3. Thc ncw namcs arc
s_ann, s_burt, and s_charles.
.12.5
Crcatc a ncw uscrdclincd databasc rolc callcd managers and add thrcc mcmbcrs (scc
.12.4) to thc rolc. Altcr that, display thc inlormation lor this rolc and its mcmbcrs.
Cha pt er l 2: S ec ur i t y Sys t em of Da t a ba s e Lngi ne 341
.12.6
Using thc GRANT statcmcnt, allow thc uscr s_burt to crcatc tablcs and thc uscr s_ann
to crcatc storcd proccdurcs in thc sample databasc.
.12.7
Using thc GRANT statcmcnt, allow thc uscr s_charles to updatc thc columns lname
and fname ol thc employee tablc.
.12.8
Using thc GRANT statcmcnt, allow thc uscrs s_burt and s_ann to rcad thc valucs
lrom thc columns emp_lname and emp_fname ol thc employee tablc. (Hint: Crcatc
thc corrcsponding vicw lirst.)
.12.9
Using thc GRANT statcmcnt, allow thc uscrdclincd rolc managers to inscrt ncw rows
in thc project tablc.
.12.10
Rcvokc thc SLCT rights lrom thc uscr s_burt.
.12.11
Using TransactSQL, do not allow thc uscr s_ann to inscrt thc ncw rows in thc project
tablc cithcr dircctly or indircctly (using rolcs).
.12.12
iscuss thc dillcrcncc bctwccn thc usc ol vicws and TransactSQL statcmcnts GRANT,
NY, and R\K in rclation to sccurity.
.12.13
isplay thc cxisting inlormation about thc uscr s_ann in rclation to thc sample databasc.
(Hint: Usc thc systcm proccdurc sp_helpuser.)
This page intentionally left blank
In 7bis Cbapter
Concurrency ModeIs
7ransactions
Locking
IsoIation LeveIs
Row Versioning
Concurrcncy Control
Cbapter 13
Copyright 2008 by The McGraw-Hill Companies. Click here for terms of use.
344 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
A
s you alrcady know, data in a databasc is gcncrally sharcd bctwccn many uscr
application programs. Thc situation in which scvcral uscr application programs
rcad and writc thc samc data at thc samc timc is callcd concurrency. Thus, cach
8MS must havc somc kind ol control mcchanism to solvc concurrcncy problcms.
A high lcvcl ol concurrcncy is possiblc in a databasc systcm that can managc
many activc uscr applications without thcm intcrlcring with cach othcr. Convcrscly, a
databasc systcm in which dillcrcnt activc applications intcrlcrc with cach othcr support
a low lcvcl ol concurrcncy.
This chaptcr bcgins by dcscribing thc two concurrcncy control modcls that atabasc
nginc supports. Thc ncxt scction cxplains how concurrcncy problcms can bc solvcd
using transactions. This discussion includcs an introduction ol thc lour propcrtics ol
transactions, known as AC! propcrtics, discussion ol thc TransactSQL statcmcnts
rclatcd to transactions, and an introduction ol transaction logs. Thc third major scction
addrcsscs locking and thc thrcc gcncral lock propcrtics: lock modcs, lock rcsourccs, and
lock duration. cadlock, an important problcm that can arisc as a conscqucncc ol locking,
is also introduccd.
Thc bchavior ol transactions dcpcnds on thc sclcctcd isolation lcvcl. Fivc lorms ol
isolation lcvcls arc introduccd, including whcthcr cach bclongs to thc pcssimistic or
thc optimistic concurrcncy modcl. Thc dillcrcnccs bctwccn cxisting isolation lcvcls and
thcir practical mcaning will bc cxplaincd, too.
Thc cnd ol thc chaptcr introduccs row vcrsioning, which is how atabasc nginc
implcmcnts thc optimistic concurrcncy modcl. Thc two isolation lcvcls rclatcd to this
modclSNAPSHT and RA CMM!TT SNAPSHTarc discusscd, as
wcll as usc ol thc tempdb systcm databasc as a vcrsion storc.
Concurrency ModeIs
atabasc nginc supports two dillcrcnt concurrcncy modcls:
Pcssimistic concurrcncy
ptimistic concurrcncy
Pcssimistic concurrcncy uscs locks to block acccss to data that is uscd by anothcr proccss
at thc samc timc. !n othcr words, a databasc systcm that uscs pcssimistic concurrcncy
assumcs that a conllict bctwccn two or morc proccsscs can occur at any timc and thcrclorc
locks rcsourccs (row, pagc, tablc), as thcy arc rcquircd, lor thc duration ol a transaction. As
you will scc in thc scction "Locking," pcssimistic concurrcncy issucs sharcd locks on data
bcing rcad so that no othcr proccss can modily that data. Also, pcssimistic concurrcncy
issucs cxclusivc locks lor data bcing modilicd so that no othcr proccsscs can rcad or modily
that data.
Cha pt er l 3: Conc ur r enc y Cont r ol 345
ptimistic concurrcncy works on thc assumption that a transaction is unlikcly to
modily data that anothcr transaction is modilying at thc samc timc. atabasc nginc
supports optimistic concurrcncy so that oldcr vcrsions ol data rows arc savcd, and any
proccss that rcads thc samc data uscs thc row vcrsion that was activc whcn it startcd
rcading data. For that rcason, a proccss that modilics thc data can do so without any
limitation, bccausc all othcr proccsscs that rcad thc samc data acccss thc savcd vcrsions
ol thc data. Thc only conllict sccnario occurs whcn two or morc writc opcrations usc
thc samc data. !n that casc, thc systcm displays an crror so that thc clicnt application
can handlc it.
|e sc||cs c/ c(||m|s||: :cs:a//es:, |s ese/c||, 1e/|se1 |s c |/cc1e/ sesse. 0(||m|s||: :cs:a//es:, :cs|/c| ac/|s
cs ||e cssam(||cs ||c| /esca/:e :cs/||:|s |e|aees ma|||(|e ase/s c/e as|||e|,, cs1 c||cas |/cssc:||css |c ese:a|e
w|t|eat a.|a |ec|.. 0s|, a|es c ase/ |s c||em(||s |c :|cse 1c|c c/e /esca/:es :|e:|e1 |c 1e|e/m|se |/ cs,
:cs/||:|s |c|e c::a//e1. |/ c :cs/||:| c::a/s, ||e c((||:c||cs mas| |e (/e(ec|e1|, /es|c/|e1.
7ransactions
A transaction spccilics a scqucncc ol TransactSQL statcmcnts that is uscd by databasc
programmcrs to packagc togcthcr rcad and writc opcrations, so that thc databasc systcm
can guarantcc thc consistcncy ol data. Thcrc arc two lorms ol transactions:
mplicit
transaction unit.
Explicit Gcncrally a group ol TransactSQL statcmcnts, whcrc thc bcginning
and thc cnd ol thc group arc markcd using statcmcnts such as 8G!N
TRANSACT!N, CMM!T, and RLL8ACK.
Thc notion ol a transaction is bcst cxplaincd through an cxamplc. !n thc sample
databasc, thc cmploycc Ann Joncs should bc assigncd a ncw cmploycc numbcr. Thc
cmploycc numbcr must bc modilicd in two dillcrcnt tablcs at thc samc timc. Thc row in
thc employee tablc and all corrcsponding rows in thc works_on tablc must bc modilicd
at thc samc timc. (!l only onc ol thcsc tablcs is modilicd, data in thc sample databasc
would bc inconsistcnt, bccausc thc valucs ol thc primary kcy in thc employee tablc and
thc corrcsponding valucs ol thc lorcign kcy in thc works_on tablc lor Mrs. Joncs would
not match.)
xamplc 13.1 shows how you can implcmcnt thc problcm discusscd abovc using
TransactSQL statcmcnts.
346 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
XAMPL 13.1
US samplc,
8G!N TRANSACT!N / Thc bcginning ol thc transaction /
UPAT cmploycc
ST cmp_no - 39831
VHR cmp_no - 10102
!F (CCcrror ~ 0)
RLL8ACK / Rollback ol thc transaction /
UPAT works_on
ST cmp_no - 39831
VHR cmp_no - 10102
!F (CCcrror ~ 0)
RLL8ACK
CMM!T /Thc cnd ol thc transaction /
Thc consistcnt statc ol data uscd in xamplc 13.1 can bc obtaincd only il both
UPAT statcmcnts arc cxccutcd or ncithcr ol thcm is cxccutcd. Thc global variablc
error is uscd to tcst thc cxccution ol cach TransactSQL statcmcnt. !l an crror occurs,
error is sct to a ncgativc valuc and thc cxccution ol all statcmcnts is rollcd back. (Thc
TransactSQL statcmcnts 8G!N TRANSACT!N, CMM!T, and RLL8ACK
arc dclincd in thc upcoming scction "TransactSQL Statcmcnts and Transactions.")
|e /cssc:|-:9| |csace sa((c/|s es:e(||css. |ss|ec1 c/ as|s ||e |c|c| |c/|c||e yyettet, ase1 |s
|scm(|e !?.!, ,ca :cs ase | cs1 t/t| s|c|emes|s |c |m(|emes| es:e(||cs |cs1||s |s c |/cssc:||cs.
|e ase c/ ||ese s|c|emes|s |s 1|s:asse1 |s t|c(|e/ ?.
Thc ncxt scction cxplains thc AC! propcrtics ol transactions. Thcsc propcrtics
guarantcc that thc data uscd by application programs will bc consistcnt.
Properties of 7ransactions
Transactions havc thc lollowing propcrtics, which arc known collcctivcly by thc
acronym AC!:
Atomicity
Consistcncy
!solation
urability
Cha pt er l 3: Conc ur r enc y Cont r ol 347
Thc atomicity propcrty guarantccs thc indivisibility ol a sct ol statcmcnts that
modilics data in a databasc and is part ol a transaction. This mcans that cithcr all data
modilications in a transaction arc cxccutcd or, in thc casc ol any lailurc, all alrcady
cxccutcd changcs arc undonc.
Consistcncy guarantccs that a transaction will not allow thc databasc to contain
inconsistcnt data. !n othcr words, thc transactional translormations on data bring thc
databasc lrom onc consistcnt statc to anothcr.
Thc isolation propcrty scparatcs concurrcnt transactions lrom cach othcr. !n othcr
words, an activc transaction can't scc data modilications in a concurrcnt and incomplctc
transaction. This mcans that somc transactions might bc rollcd back to guarantcc isolation.
urability guarantccs onc ol thc most important databasc conccpts: pcrsistcncc ol
data. This propcrty cnsurcs that thc cllccts ol thc particular transaction pcrsist cvcn il a
systcm crror occurs. For this rcason, il a systcm crror occurs whilc a transaction is activc,
all statcmcnts ol that transaction will bc undonc.
7ransact-SL Statements and 7ransactions
Thcrc arc six TransactSQL statcmcnts rclatcd to transactions:
8G!N TRANSACT!N
8G!N !STR!8UT TRANSACT!N
CMM!T |VRK|
RLL8ACK |VRK|
SA\ TRANSACT!N
ST !MPL!C!T_TRANSACT!NS
Thc 8G!N TRANSACT!N statcmcnt starts thc transaction. !t has thc lollowing
syntax:
8G!N TRANSACT!N | [transaction_namc ] Ctrans_var ]
|V!TH MARK |'dcscription'|||
transaction_name is thc namc assigncd to thc transaction, which can bc uscd only
on thc outcrmost pair ol ncstcd 8G!N TRANSACT!N/CMM!T or 8G!N
TRANSACT!N/RLL8ACK statcmcnts. trans_var is thc namc ol a uscrdclincd
variablc containing a valid transaction namc. Thc V!TH MARK option spccilics
that thc transaction is to bc markcd in thc log. description is a string that dcscribcs
thc mark. !l V!TH MARK is uscd, a transaction namc must bc spccilicd. (For morc
inlormation on transaction log marking lor rccovcry, scc Chaptcr 17.)
348 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Thc 8G!N !STR!8UT TRANSACT!N statcmcnt spccilics thc start ol a
distributcd transaction managcd by thc Microsolt istributcd Transaction Coordinator
(MS TC). A distributed transaction is onc that involvcs databascs on morc than onc
scrvcr. For this rcason, whcrc is a nccd lor a coordinator, which will coordinatc cxccution
ol statcmcnts on all involvcd scrvcrs. Thc scrvcr cxccuting thc 8G!N !STR!8UT
TRANSACT!N statcmcnt is thc transaction coordinator and thcrclorc controls thc
complction ol thc distributcd transaction. (Scc Chaptcr 19 lor a discussion ol distributcd
transactions.)
Thc CMM!T VRK statcmcnt succcsslully cnds thc transaction startcd with thc
8G!N TRANSACT!N statcmcnt. This mcans that all modilications madc by thc
transaction arc storcd on thc disk. Thc CMM!T VRK statcmcnt is a standardizcd
SQL statcmcnt. (Thc VRK clausc is optional.)
|e /cssc:|-:9| |csace c|sc sa((c/|s ||e t0//| |/|:/t|0| s|c|emes|, a||:| |s /as:||csc||, ea| |c|es|
|c t0//| 0||, a||| ||e es:e(||cs ||c| ||e /c/me/ c::e(|s c ase/-1e/|se1 |/cssc:||cs scme. t0//|
|/|:/t|0| |s cs es|ess|cs c/ /cssc:|-:9| |s /e|c||cs |c ||e :9| s|cs1c/1.
!n contrast to thc CMM!T statcmcnt, thc RLL8ACK VRK statcmcnt
rcports an unsucccsslul cnd ol thc transaction. Programmcrs usc this statcmcnt il thcy
assumc that thc databasc might bc in an inconsistcnt statc. !n this casc, all cxccutcd
modilication opcrations within thc transaction arc rollcd back. Thc RLL8ACK
VRK statcmcnt is a standardizcd SQL statcmcnt. (Thc VRK clausc is optional.)
/cssc:|-:9| c|sc sa((c/|s ||e |0||3/t| |/|:/t|0| s|c|emes|, a||:| |s /as:||csc||, ea||c|es| |c
|0||3/t| 0||, a||| ||e es:e(||cs ||c| |0||3/t| |/|:/t|0| c::e(|s c ase/-1e/|se1 |/cssc:||cs scme.
Thc SA\ TRANSACT!N statcmcnt scts a savcpoint within a transaction.
A sa.epoint marks a spccilicd point within thc transaction so that all updatcs that
lollow can bc cancclcd without canccling thc cntirc transaction. (To canccl an cntirc
transaction, usc thc RLL8ACK statcmcnt.)
|e :/l| |/|:/t|0| s|c|emes| c:|ac||, 1ces sc| :cmm|| cs, mc1|/|:c||cs c(e/c||cs, || cs|, :/ec|es c
|c/e| /c/ ||e sa|seaes| |0||3/t| s|c|emes| a||| ||e |c|e| a||| ||e scme scme cs ||e :/l| |/|:/t| 0|
s|c|emes|.
Cha pt er l 3: Conc ur r enc y Cont r ol 349
xamplc 13.2 shows thc usc ol thc SA\ TRANSACT!N statcmcnt.
XAMPL 13.2
8G!N TRANSACT!N,
!NSRT !NT dcpartmcnt (dcpt_no, dcpt_namc)
\ALUS ('d4', 'Salcs'),
SA\ TRANSACT!N a,
!NSRT !NT dcpartmcnt (dcpt_no, dcpt_namc)
\ALUS ('d5', 'Rcscarch'),
SA\ TRANSACT!N b,
!NSRT !NT dcpartmcnt (dcpt_no, dcpt_namc)
\ALUS ('d6', 'Managcmcnt'),
RLL8ACK TRANSACT!N b,
!NSRT !NT dcpartmcnt (dcpt_no, dcpt_namc)
\ALUS ('d7', 'Support'),
RLL8ACK TRANSACT!N a,
CMM!T TRANSACT!N,
Thc only statcmcnt in xamplc 13.2 that is cxccutcd is thc lirst !NSRT statcmcnt.
Thc third !NSRT statcmcnt is rollcd back by thc RLL8ACK b statcmcnt, whilc
thc othcr two !NSRT statcmcnts arc rollcd back by thc RLL8ACK a statcmcnt.
|e :/l| |/|:/t|0| s|c|emes|, |s :cm||sc||cs a||| ||e || c/ |||| s|c|emes|, |s c ase/a| |/cssc:|| cs
/ec|a/e /c/ ||e ese:a||cs c/ (c/|s c/ cs es||/e |/cssc:||cs. 0s ||e c||e/ |cs1, ||e ase c/ |||s s|c|emes| |s
:cs|/c/, |c ||e (/|s:|(|e c/ c(e/c||csc| 1c|c|cses ||c| c |/cssc:||cs s|ca|1 |e cs s|c/| cs (css|||e, |e:case |cs
|/cssc:||css ese/c||, /e1a:e 1c|c c|c||c|||||,.
As you alrcady know, cach TransactSQL statcmcnt always bclongs cithcr implicitly or
cxplicitly to a transaction. atabasc nginc providcs implicit transactions lor compliancc
with thc SQL standard. Vhcn a scssion opcratcs in thc implicit transaction modc, sclcctcd
statcmcnts implicitly issuc thc 8G!N TRANSACT!N statcmcnt. This mcans that you
do nothing to start an implicit transaction. Howcvcr, thc cnd ol cach implicit transaction
must bc cxplicitly committcd or rollcd back using thc CMM!T or RLL8ACK
statcmcnt. (!l you do not cxplicitly commit thc transaction, thc transaction and all thc data
changcs it contains arc rollcd back whcn thc uscr disconnccts.)
To cnablc an implicit transaction, you havc to cnablc thc !MPL!C!T_
TRANSACT!NS clausc ol thc ST statcmcnt. This statcmcnt scts thc implicit
transaction modc lor thc currcnt scssion. Vhcn a conncction is in thc implicit
350 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
transaction modc and thc conncction is not currcntly in a transaction, cxccuting any
ol thc lollowing statcmcnts starts a transaction:
ALTR TA8L FTCH R\K
CRAT TA8L GRANT SLCT
LT !NSRT TRUNCAT TA8L
RP TA8L PN UPAT
!n othcr words, il you havc a scqucncc ol statcmcnts lrom thc prcccding list, cach
statcmcnt will rcprcscnt a singlc transaction.
Thc bcginning ol an cxplicit transaction is markcd with thc 8G!N TRANSACT!N
statcmcnt. Thc cnd ol an cxplicit transaction is markcd with thc CMM!T or
RLL8ACK statcmcnt. xplicit transactions can bc ncstcd. !n this casc, cach pair ol
statcmcnts 8G!N TRANSACT!N/CMM!T or 8G!N TRANSACT!N/
RLL8ACK is uscd insidc onc or morc such pairs. (Thc ncstcd transactions arc usually
uscd in storcd proccdurcs, which thcmsclvcs contain transactions and arc invokcd insidc
anothcr transaction.) Thc global variablc trancount contains thc numbcr ol activc
transactions lor thc currcnt uscr.
8G!N TRANSACT!N, CMM!T, and RLL8ACK can bc spccilicd using
a namc assigncd to thc transaction. (Thc namcd RLL8ACK statcmcnt corrcsponds
cithcr to a namcd transaction or to thc SA\ TRANSACT!N statcmcnt with thc
samc namc.) You can usc a namcd transaction only in thc outcrmost statcmcnt pair
ol ncstcd 8G!N TRANSACT!N/CMM!T or 8G!N TRANSACT!N/
RLL8ACK statcmcnts.
7ransaction Log
Rclational databasc systcms kccp a rccord ol cach changc thcy makc to thc databasc
during a transaction. This is ncccssary in casc an crror occurs during thc cxccution
ol thc transaction. !n this situation, all prcviously cxccutcd statcmcnts within thc
transaction havc to bc rollcd back. As soon as thc systcm dctccts thc crror, it uscs
thc storcd rccords to rcturn thc databasc to thc consistcnt statc that cxistcd bclorc
thc transaction was startcd.
atabasc nginc kccps all storcd rccords, in particular thc bclorc and altcr valucs, in
onc or morc lilcs callcd thc transaction log. ach databasc has its own transaction log.
Thus, il it is ncccssary to roll back onc or morc modilication opcrations cxccutcd on thc
tablcs ol thc currcnt databasc, atabasc nginc uscs thc cntrics in thc transaction log to
rcstorc thc valucs ol columns that thc databasc had bclorc thc transaction was startcd.
Thc transaction log is uscd to roll back or rcstorc a transaction. !l an crror occurs and
thc transaction docs not complctcly cxccutc, thc systcm uscs all cxisting bclorc valucs
Cha pt er l 3: Conc ur r enc y Cont r ol 351
lrom thc transaction log (callcd before images) to roll back all modilications sincc thc
start ol thc transaction. Thc proccss in which bclorc imagcs lrom thc transaction log arc
uscd to roll back all modilications is callcd thc undo activity.
Transaction logs also storc so callcd altcr imagcs. fter images arc all altcr valucs, which
arc uscd to roll lorward all modilications sincc thc start ol thc transaction. This proccss
is callcd thc redo activity and is applicd during rccovcry ol a databasc. (For lurthcr dctails
conccrning transaction logs and rccovcry, scc Chaptcr 17.)
vcry cntry writtcn into thc log is uniqucly idcntilicd using thc log scqucncc numbcr
(LSN). All log cntrics that arc part ol thc particular transaction arc linkcd togcthcr, so
that all parts ol a transaction can bc locatcd lor undo and rcdo activitics.
Locking
Concurrcncy can lcad to scvcral ncgativc cllccts, such as thc rcading ol noncxistcnt
data or loss ol modilicd data. Considcr this rcalworld cxamplc illustrating onc ol thcsc
ncgativc cllccts, callcd dirty read: Uscr U
1
in thc pcrsonncl dcpartmcnt gcts noticc ol an
addrcss changc lor thc cmploycc Jim Smith. U
1
makcs thc addrcss changc, but whcn
vicwing thc bank account inlormation ol Mr. Smith in thc consccutivc dialog stcp, hc
rcalizcs that hc modilicd thc addrcss ol thc wrong pcrson. (Thc cntcrprisc cmploys
two pcrsons with thc namc Jim Smith.) Fortunatcly, thc application allows thc uscr
to canccl this changc by clicking a button. U
1
clicks thc button, knowing that hc has
committcd no crror.
At thc samc timc, uscr U
2
in thc tcchnical dcpartmcnt rctricvcs thc data ol thc lattcr
Mr. Smith to scnd thc ncwcst tcchnical documcnt to his homc, bccausc thc cmploycc
scldom comcs to thc ollicc. As thc cmploycc's addrcss was wrongly changcd just bclorc
U
2
rctricvcd thc addrcss, U
2
prints out thc wrong addrcss labcl and scnds thc documcnt
to thc wrong pcrson.
To prcvcnt problcms likc thcsc in thc pcssimistic concurrcncy modcl, cvcry 8MS
must havc mcchanisms that control thc acccss ol data by all uscrs at thc samc timc.
atabasc nginc, likc all rclational 8MSs, uscs locks to guarantcc thc consistcncy
ol thc databasc in casc ol multiuscr acccss. ach application program locks thc data it
nccds, guarantccing that no othcr program can modily thc samc data. Vhcn anothcr
application program rcqucsts thc modilication ol thc lockcd data, thc systcm cithcr
stops thc program with an crror or makcs a program wait.
Locking has scvcral dillcrcnt aspccts:
Lock duration
Lock modcs
Lock granularity
352 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Lock duration spccilics a timc pcriod during which a rcsourcc holds thc particular
lock. uration ol a lock dcpcnds on, among othcr things, thc modc ol thc lock and thc
choicc ol thc isolation lcvcl.
Thc ncxt two scctions dcscribc lock modcs and lock granularity.
|e /c||ca|s 1|s:ass|cs :cs:e/ss ||e (ess|m|s||: :cs:a//es:, mc1e|. |e c(||m|s||: :cs:a//es:, mc1e| |s
|cs1|e1 as|s /ca |e/s|cs|s, cs1 a||| |e es(|c|se1 c| ||e es1 c/ |||s :|c(|e/.
Lock Modes
Lock modcs spccily dillcrcnt kinds ol locks. Thc choicc ol which lock modc to apply
dcpcnds on thc rcsourcc that nccds to bc lockcd. Thc lollowing thrcc lock typcs arc
uscd lor row and pagclcvcl locking:
Sharcd (S)
xclusivc (X)
Updatc (U)
A shared lock rcscrvcs a rcsourcc (pagc or row) lor rcading only. thcr proccsscs cannot
modily thc lockcd rcsourcc whilc thc lock rcmains. n thc othcr hand, scvcral proccsscs
can hold a sharcd lock lor a rcsourcc at thc samc timcthat is, scvcral proccsscs can rcad
thc rcsourcc lockcd with thc sharcd lock.
An exclusi.e lock rcscrvcs a pagc or row lor thc cxclusivc usc ol a singlc transaction.
!t is uscd lor ML statcmcnts (!NSRT, UPAT, and LT) that modily
thc rcsourcc. An cxclusivc lock cannot bc sct il somc othcr proccss holds a sharcd
or cxclusivc lock on thc rcsourccthat is, thcrc can bc only onc cxclusivc lock lor
a rcsourcc. ncc an cxclusivc lock is sct lor thc pagc (or row), no othcr lock can bc
placcd on thc samc rcsourcc.
|ce-|e|e| |c:||s c|sc c||cas cs |s|es| |c:|, 1es:/||e1 |c|e/ |s |||s se:||cs.
An update lock can bc placcd only il no othcr updatc or cxclusivc lock cxists. n thc
othcr hand, it can bc placcd on objccts that alrcady havc sharcd locks. (!n this casc,
thc updatc lock acquircs anothcr sharcd lock on thc samc objcct.) !l a transaction that
Cha pt er l 3: Conc ur r enc y Cont r ol 353
modilics thc objcct is committcd, thc updatc lock is changcd to an cxclusivc lock il
thcrc arc no othcr locks on thc objcct. Thcrc can bc only onc updatc lock lor an objcct.
|(1c|e |c:|s (/e|es| :e/|c|s :cmmcs |,(es c/ 1ec1|c:|s. (|ec1|c:|s c/e 1es:/||e1 c| ||e es1 c/ |||s se:||cs.
Tablc 131 shows thc compatibility matrix lor sharcd, cxclusivc, and updatc locks.
Thc matrix is intcrprctcd as lollows: supposc transaction T
1
holds a lock as spccilicd in
thc lirst column ol thc matrix, and supposc somc othcr transaction, T
2
,
rcqucsts a lock as
spccilicd in thc corrcsponding column hcading. !n this casc, "ycs" indicatcs that a lock
ol T
2
is possiblc, whcrcas "no" indicatcs a conllict with thc cxisting lock.
|c|c|cse |s|se c|sc sa((c/|s c||e/ |c:| /c/ms, sa:| cs |c|:|es cs1 s(|s|c:|s. |e 1es:/|(||cs c/ ||ese |c:|
/c/ms :cs |e /cas1 |s 3cc|s 0s||se.
At thc tablc lcvcl, thcrc arc livc dillcrcnt typcs ol locks:
Sharcd (S)
xclusivc (X)
!ntcnt sharcd (!S)
!ntcnt cxclusivc (!X)
Sharcd with intcnt cxclusivc (S!X)
Sharcd and cxclusivc locks corrcspond to thc rowlcvcl (or pagclcvcl) locks with
thc samc namcs. Gcncrally, an intent lock shows an intcntion to lock thc ncxtlowcr
rcsourcc in thc hicrarchy ol thc databasc objccts. Thcrclorc, intcnt locks arc placcd at
!hare6 0p6ate lxc|cs|e
!hare6 \e. \e. Ne
0p6ate \e. Ne Ne
lxc|cs|e Ne Ne Ne
Iah|e 11-1 tcm(c|||||||, /c|/|s /c/ :|c/e1, |s:|as||e, cs1 |(1c|e |c:|s
354 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
a lcvcl in thc objcct hicrarchy abovc that which thc proccss intcnds to lock. This is an
cllicicnt way to tcll whcthcr such locks will bc possiblc, and it prcvcnts othcr proccsscs
lrom locking thc highcr lcvcl bclorc thc dcsircd locks can bc attaincd.
Tablc 132 shows thc compatibility matrix lor all kinds ol tablc locks. Thc matrix is
intcrprctcd cxactly as thc matrix in Tablc 131.
Lock CranuIarity
Lock granularity spccilics which rcsourcc is lockcd by a singlc lock attcmpt. atabasc
nginc can lock thc lollowing rcsourccs:
Row
Pagc
!ndcx kcy or rangc ol indcx kcys
Tablc
xtcnt
atabasc itscll
|e s,s|em ca|cmc||:c||, :|ccses ||e c((/c(/|c|e |c:| /csa|c/||,.
A row is thc smallcst rcsourcc that can bc lockcd. Thc support ol rowlcvcl locking
includcs both data rows and indcx cntrics. Rowlcvcl locking mcans that only thc row
that is acccsscd by an application will bc lockcd. Hcncc, all othcr rows that bclong to
! K |! !|K |K
! \e. Ne \e. Ne Ne
K Ne Ne Ne Ne Ne
|! \e. Ne \e. \e. \e.
!|K Ne Ne \e. Ne Ne
|K Ne Ne \e. Ne \e.
Iah|e 11-1 tcm(c|||||||, /c|/|s /c/ /|| ||s1s c/ c||e |c:|s
Cha pt er l 3: Conc ur r enc y Cont r ol 355
thc samc pagc arc lrcc and can bc uscd by othcr applications. atabasc nginc can also
lock thc pagc on which thc row that has to bc lockcd is storcd.
|/ c |c||e |s :|as|e/e1, ||e 1c|c (ces c/e s|c/e1 c| ||e |ec/ |e|e| c/ ||e (:|as|e/e1 |s1es s|/a:|a/e cs1 c/e
||e/e/c/e |c:|e1 a||| |s1es |e, |c:|s |ss|ec1 c/ /ca |c:|s.
Locking is also donc on disk units, callcd extents, that arc 64K in sizc (scc Chaptcr 15).
xtcnt locks arc sct automatically whcn a tablc (or indcx) grows and thc additional disk
spacc is nccdcd.
Lock granularity allccts concurrcncy. !n gcncral, thc largcr thc lock granularity
uscd, thc morc concurrcncy is rcduccd. This mcans that rowlcvcl locking maximizcs
concurrcncy bccausc it lcavcs all but onc row on thc pagc unlockcd. n thc othcr
hand, systcm ovcrhcad is incrcascd bccausc cach lockcd row rcquircs onc lock. Pagc
lcvcl locking (and tablclcvcl locking) rcstricts thc availability ol data but dccrcascs thc
systcm ovcrhcad.
Lock scaIation
!l many locks ol thc samc lock granularity arc hcld during a transaction, atabasc
nginc automatically upgradcs thcsc locks into a tablc lock. This proccss ol convcrting
many pagc, row, or indcxlcvcl locks into onc tablc lock is callcd lock escalation. Thc
cscalation thrcshold is thc boundary at which thc databasc systcm applics thc lock
cscalation. scalation thrcsholds arc dctcrmincd dynamically by thc systcm and rcquirc
no conliguration. (Currcntly, thc amount ol thrcshold boundary is 5000 locks.)
Thc gcncral problcm with lock cscalation is that thc databasc scrvcr dccidcs whcn to
cscalatc a particular lock, and this dccision might bc suboptimal lor applications with
dillcrcnt rcquircmcnts. For this rcason, SQL Scrvcr 2008 cnhanccs thc syntax ol thc
ALTR TA8L statcmcnt to allow you to changc thc lock cscalation mcchanism. This
statcmcnt now supports thc TA8L option with thc lollowing syntax:
ST ( LCK_SCALAT!N - [ TA8L ] AUT ] !SA8L ] )
Thc TA8L option is thc dclault valuc and it spccilics that lock cscalation will bc
donc at tablclcvcl granularity. (This bchavior is thc samc as in SQL Scrvcr 2005.) Thc
AUT option allows atabasc nginc to sclcct thc lock cscalation granularity that is
appropriatc lor thc tablc schcma. Finally, thc !SA8L option allows you to disablc
lock cscalation in most cascs. (Thcrc arc samc cascs in which atabasc nginc must
takc a tablc lock to protcct data intcgrity.)
356 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
xamplc 13.3 disablcs thc lock cscalation lor thc employee tablc.
XAMPL 13.3
US samplc,
ALTR TA8L cmploycc ST (LCK_SCALAT!N - !SA8L),
Affecting Locks
You can usc cithcr locking hints or thc LCK_T!MUT option ol thc ST
statcmcnt to allcct locks. Thc lollowing subscctions dcscribc thcsc lcaturcs.
Locking Hints
Locking hints spccily thc typc ol locking uscd by atabasc nginc to lock tablc data.
Tablclcvcl locking hints can bc uscd whcn lincr control ol thc typcs ol locks acquircd
on a rcsourcc is rcquircd. (Locking hints ovcrridc thc currcnt transaction isolation lcvcl
lor thc scssion.)
All locking hints arc writtcn as a part ol thc FRM clausc in thc SLCT
statcmcnt. You can usc thc lollowing locking hints:
UPDLOCK Placcs updatc locks lor cach row ol thc tablc during thc rcad
opcration. All updatc locks arc hcld until thc cnd ol thc transaction.
TABLOCK (TABLOCKX) Placcs a sharcd (or cxclusivc) tablc lock on thc
tablc. All locks arc hcld until thc cnd ol thc transaction.
ROWLOCK Rcplaccs thc cxisting sharcd tablc lock with sharcd row locks lor
cach qualilying row ol thc tablc.
PAGLOCK Rcplaccs a sharcd tablc lock with sharcd pagc locks lor cach pagc
containing qualilying rows.
NOLOCK Synonym lor RAUNCMM!TT (scc thc dcscription ol
isolationlcvcl hints latcr in this chaptcr).
HOLDLOCK Synonym lor RPATA8LRA (scc thc dcscription ol
isolationlcvcl hints latcr in this chaptcr).
XLOCK
TA8LCK, thc cxclusivc locks apply to thc appropriatc lcvcl ol granularity.
READPAST
by othcr transactions.
Cha pt er l 3: Conc ur r enc y Cont r ol 357
/|| ||ese c(||css :cs |e :cm||se1 |s cs, c/1e/ |/ ||e :cm||sc||cs mc|es sesse. (|c/ escm(|e, ||e :cm||sc||cs
|e|aees /3|0t| cs1 |/|0t| |s sesse|ess, |e:case |c|| c(||css c/e c((||e1 |c 1|//e/es| /esca/:es.
LOCk_7IMOU7 Option
Thc LCK_T!MUT option ol thc ST statcmcnt can bc uscd to spccily thc
numbcr ol milliscconds a transaction will wait lor a lock to bc rclcascd. Thc valuc ol 1
(thc dclault valuc) indicatcs no timcout, in othcr words, thc transaction won't wait at
all. (Thc RAPAST locking hint providcs an altcrnativc to this ST option.)
DispIaying Lock Information
Lock inlormation can bc displaycd using cithcr thc sp_lock systcm proccdurc or thc
dynamic managcmcnt vicw callcd sys.dm_tran_locks. 8ccausc sp_lock is a dcprccatcd
lcaturc and won't bc supportcd in thc ncxt rclcasc ol SQL Scrvcr, this scction dcscribcs
only thc sys.dm_tran_locks vicw.
sys.dm_tran_locks. Thc vicw rcturns inlormation about currcntly activc lock managcr
rcsourccs. ach row rcprcscnts a currcntly activc rcqucst lor a lock that has bccn grantcd
or is waiting to bc grantcd. Thc columns ol this vicw rclatc to two groups: rcsourcc and
rcqucst. Thc rcsourcc group dcscribcs thc rcsourcc on which thc lock rcqucst is bcing
madc, and thc rcqucst group dcscribcs thc lock rcqucst. Thc most important columns ol
this vicw arc as lollows:
resource_type Rcprcscnts thc rcsourcc typc
resource_database_id
rcsourcc is scopcd
request_mode
request_status
xamplc 13.4 displays all thc locks that arc in a wait statc.
XAMPL 13.4
SLCT rcsourcc_typc, 8_NAM(rcsourcc_databasc_id) as db_namc,
rcqucst_scssion_id, rcqucst_modc, rcqucst_status
FRM sys.dm_tran_locks
VHR rcqucst_status - 'VA!T,'
358 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
DeadIock
A deadlock is a spccial concurrcncy problcm in which two transactions block thc
progrcss ol cach othcr. Thc lirst transaction has a lock on somc databasc objcct that
thc othcr transaction wants to acccss, and vicc vcrsa. (!n gcncral, scvcral transactions
can causc a dcadlock by building a circlc ol dcpcndcncics.) xamplc 13.5 shows thc
dcadlock situation bctwccn two transactions.
|e (c/c||e||sm c/ (/c:esses :cssc| |e c:||e|e1 sc|a/c||, as|s ||e smc|| sem/e 1c|c|cse, |e:case e|e/,
|/cssc:||cs |s || |s ese:a|e1 |e/, a|:||,. |e/e/c/e, |scm(|e !?.: ases ||e /||0| s|c|emes| |c (case |c||
|/cssc:||css /c/ |es se:cs1s |c s|ma|c|e ||e 1ec1|c:|.
XAMPL 13.5
8G!N TRANSACT!N
UPAT works_on
ST job - 'Managcr'
VHR cmp_no - 18316
AN projcct_no - 'p2'
VA!TFR LAY '00:00:10'
UPAT cmploycc
ST cmp_lnamc - 'Grccn'
VHR cmp_no - 9031
CMM!T
8G!N TRANSACT!N
UPAT cmploycc
ST dcpt_no - 'd2'
VHR cmp_no - 9031
VA!TFR LAY '00:00:10'
LT FRM works_on
VHR cmp_no - 18316
AN projcct_no - 'p2'
CMM!T
!l both transactions in xamplc 13.5 arc cxccutcd at thc samc timc, thc dcadlock
appcars and thc systcm rcturns thc lollowing output:
Scrvcr: Msg 1205, Lcvcl 13, Statc 45
Transaction (Proccss id 56) was dcadlockcd with anothcr proccss and has bccn
choscn as dcadlock victim. Rcrun your command.
As thc output ol xamplc 13.5 shows, thc databasc systcm handlcs a dcadlock by
choosing onc ol thc transactions as a "victim" (actually, thc onc that closcd thc loop
in lock rcqucsts) and rolling it back. (Thc othcr transaction is cxccutcd altcr that.)
A programmcr can handlc a dcadlock by implcmcnting thc conditional statcmcnt
that tcsts lor thc rcturncd crror numbcr (1205) and thcn cxccutcs thc rollcdback
transaction again.
You can allcct which transaction thc systcm chooscs as thc "victim" by using thc
ALCK_PR!R!TY option ol thc ST statcmcnt. Thcrc arc 21 dillcrcnt
Cha pt er l 3: Conc ur r enc y Cont r ol 359
priority lcvcls, lrom 10 to 10. Thc valuc LV corrcsponds to 5, NRMAL (thc
dclault valuc) corrcsponds to 0, and H!GH corrcsponds to 5. Thc "victim" scssion is
choscn according to thc scssion's dcadlock priority.
IsoIation LeveIs
!n thcory, cach transaction should bc lully isolatcd lrom othcr transactions. 8ut, in such a
casc, data availability is signilicantly rcduccd, bccausc rcad opcrations in a transaction block
writc opcrations in othcr transactions, and vicc vcrsa. !l data availability is an important
issuc, this propcrty can bc looscncd using isolation lcvcls. Isolation le.els spccily thc dcgrcc
to which data bcing rctricvcd in a transaction is protcctcd lrom changcs to thc samc
data by othcr transactions. 8clorc you arc introduccd to thc cxisting isolation lcvcls, thc
lollowing scction takcs a look at sccnarios that can arisc il locking isn't uscd and, hcncc,
thcrc is no isolation bctwccn transactions.
Concurrency ProbIems
!l locking isn't uscd and thus no isolation cxists bctwccn transaction, thc lollowing lour
problcms may appcar:
Lost updatc
irty rcads (discusscd carlicr, in thc "Locking" scction)
Nonrcpcatablc rcads
Phantoms
Thc lost update concurrcncy problcm occurs whcn no isolation is providcd to a
transaction lrom othcr transactions. This mcans that scvcral transactions can rcad thc
samc data and modily it. Thc changcs to thc data by all transactions, cxccpt thosc by thc
last transaction, arc lost.
Thc nonrepeatable read concurrcncy problcm occurs whcn onc proccss rcads data
scvcral timcs, and anothcr proccss changcs thc samc data bctwccn two rcad opcrations
ol thc lirst onc. Thcrclorc, thc valucs rcad by both rcad opcrations arc dillcrcnt.
Thc phantom concurrcncy problcm is similar to thc nonrcpcatablc rcad concurrcncy
problcm, bccausc two subscqucnt rcad opcrations can display dillcrcnt valucs, but in
this casc, thc rcason lor this bchavior lics in thc dillcrcnt numbcr ol rows bcing rcad thc
lirst timc and thc sccond timc. (Additional rows, callcd phantoms, arc inscrtcd by othcr
transactions.)
360 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Database ngine and IsoIation LeveIs
Using isolation lcvcls, you can spccily which ol thc concurrcncy problcms may occur
and which you want to avoid. atabasc nginc supports thc lollowing livc isolation
lcvcls, which control how your rcad opcrations arc cxccutcd:
RA UNCMM!TT
RA CMM!TT
RPATA8L RA
SR!AL!ZA8L
SNAPSHT
RA UNCMM!TT, RPATA8L RA, and SR!AL!ZA8L arc
availablc only in thc pcssimistic concurrcncy modcl, whcrcas SNAPSHT is availablc
only in thc optimistic concurrcncy modcl. RA CMM!TT is availablc in both
modcls. Thc lour isolation lcvcls availablc in thc pcssimistic concurrcncy modcl arc
dcscribcd ncxt. SNAPSHT is dcscribcd in thc ncxt scction, "Row \crsioning."
RAD UNCOMMI77D
RA UNCMM!TT providcs thc simplcst lorm ol isolation bctwccn transactions,
bccausc it docs not isolatc thc rcad opcrations lrom othcr transactions at all. Vhcn a
transaction rctricvcs a row at this isolation lcvcl, it acquircs no locks and rcspccts nonc ol
thc cxisting locks. Thc data that is rcad by such a transaction may bc inconsistcnt. !n this
casc, a transaction rcads data that is updatcd lrom somc othcr activc transaction. !l thc
lattcr transaction rolls back latcr, thc lormcr transaction rcads data that ncvcr rcally cxistcd.
l thc lour concurrcncy problcms dcscribcd in thc prcccding scction, RA
UNCMM!TT allows dirty rcads, nonrcpcatablc rcads, and phantoms.
|e ||/| ||t0//||| |sc|c||cs |e|e| |s asac||, |e/, as1es|/c||e cs1 s|ca|1 |e ase1 cs|, a|es ||e c::a/c:,
c/ ||e 1c|c /ec1 |s sc| |m(c/|cs| c/ ||e 1c|c |s se|1cm mc1|/|e1.
RAD COMMI77D
As you alrcady know, thc RA CMM!TT isolation lcvcl has two lorms. Thc
lirst lorm applics to thc pcssimistic concurrcncy modcl, whilc thc sccond lorm applics
to thc optimistic concurrcncy modcl. This scction discusscs thc lormcr. Thc sccond
Cha pt er l 3: Conc ur r enc y Cont r ol 361
lorm, RA CMM!TT SNAPSHT, is discusscd in thc lollowing scction,
"Row \crsioning."
A transaction that rcads a row and uscs thc RA CMM!TT isolation lcvcl
tcsts only whcthcr an cxclusivc lock is placcd on thc row. !l no such lock cxists, thc
transaction lctchcs thc row. (This is donc using a sharcd lock.) This action prcvcnts thc
transaction lrom rcading data that is not committcd and that can bc subscqucntly rollcd
back. Altcr rcading thc data valucs, thc data can bc changcd by somc othcr transaction.
Sharcd locks uscd by this isolation lcvcl arc rclcascd immcdiatcly altcr thc data
is proccsscd. (Gcncrally, all locks arc rclcascd at thc cnd ol thc transaction.) For this
rcason, thc acccss to thc concurrcnt data is improvcd, but nonrcpcatablc rcads and
phantoms can still happcn.
|e ||/| t0//||| |sc|c||cs |e|e| |s ||e 1e/ca|| |sc|c||cs |e|e| c/ |c|c|cse |s|se.
RPA7A8L RAD
!n contrast to thc RA CMM!TT isolation lcvcl, RPATA8L RA
placcs sharcd locks on all data that is rcad and holds thcsc locks until thc transaction
is committcd or rollcd back. Thcrclorc, in this casc, thc cxccution ol a qucry scvcral
timcs insidc a transaction will always display thc samc rcsult. Thc disadvantagc ol this
isolation lcvcl is that concurrcncy is lurthcr rcduccd, bccausc thc timc intcrval during
which othcr transactions cannot updatc thc samc data is signilicantly longcr than in thc
casc ol RA CMM!TT.
This isolation lcvcl docs not prcvcnt anothcr transaction lrom inscrting ncw rows,
which arc includcd in subscqucnt rcads, so phantoms can appcar.
SRIALI7A8L
SR!AL!ZA8L is thc strongcst isolation lcvcl, bccausc it prcvcnts all lour concurrcncy
problcms alrcady discusscd. !t acquircs a rangc lock on all data that is rcad by thc
corrcsponding transaction. Thcrclorc, this isolation lcvcl also prcvcnts thc inscrtion ol ncw
rows by anothcr transaction until thc lormcr transaction is committcd or rollcd back.
|e :|||/||//3|| |sc|c||cs |e|e| |s |m(|emes|e1 as|s c |e,-/cse |c:||s me||c1. ||s me||c1 |c:|s |s1|||1ac|
/cas cs1 ||e /cses |e|aees ||em. / |e,-/cse |c:| c:a|/es |c:|s /c/ |s1es es|/|es /c||e/ ||cs |c:|s /c/ ||e
(c/||:a|c/ (ces c/ ||e es||/e |c||e. |s |||s :cse, cs, mc1|/|:c||cs c(e/c||cs c/ csc||e/ |/cssc:||cs :cssc| |e
ese:a|e1, |e:case ||e se:essc/, :|cses c/ |s1es es|/|es c/e sc| (css|||e.
362 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
ach isolation lcvcl in thc prcccding dcscription rcduccs thc concurrcncy morc than thc
prcvious onc. Thus, thc isolation lcvcl RA UNCMM!TT rcduccs concurrcncy
thc lcast. n thc othcr hand, it also has thc smallcst isolation lrom concurrcnt transactions.
SR!AL!ZA8L rcduccs concurrcncy thc most, but guarantccs lull isolation bctwccn
concurrcnt transactions.
Setting and diting IsoIation LeveIs
You can sct an isolation lcvcl by using thc lollowing:
!solationlcvcl hints
Thc TRANSACT!N !SLAT!N L\L option ol thc ST statcmcnt
providcs livc constant valucs, which havc thc samc namcs and mcanings as thc standard
isolation lcvcls just dcscribcd. Thc FRM clausc ol thc SLCT statcmcnt supports
scvcral hints lor isolation lcvcls:
RAUNCMM!TT
RACMM!TT
RPATA8LRA
SR!AL!ZA8L
Thcsc hints corrcspond to thc isolation lcvcls with thc samc namc (but with a spacc
in thc namc). Thc spccilication ol isolation lcvcls in thc FRM clausc ol thc SLCT
statcmcnt ovcrridcs thc currcnt valuc sct by thc ST TRANSACT!N !SLAT!N
L\L statcmcnt.
Thc 8CC USRPT!NS statcmcnt rcturns, among othcr things, inlormation
about thc isolation lcvcl. Look at thc valuc ol thc isolation lcvcl option ol this statcmcnt
to lind out thc isolation lcvcl ol your proccss.
Row Versioning
atabasc nginc supports an optimistic concurrcncy control mcchanism bascd on
row vcrsioning. Vhcn data is modilicd using row vcrsioning, logical copics ol thc data
arc maintaincd lor all data modilications pcrlormcd in thc databasc. vcry timc a row
is modilicd, thc databasc systcm storcs a bclorc imagc ol thc prcviously committcd
row in thc tempdb systcm databasc. ach vcrsion is markcd with thc transaction
Cha pt er l 3: Conc ur r enc y Cont r ol 363
scqucncc numbcr (XSN) ol thc transaction that madc thc changc. (Thc XSN is uscd to
uniqucly idcntily cach transaction.) Thc ncwcst vcrsion ol a row is always storcd in thc
databasc and chaincd in thc linkcd list to thc corrcsponding vcrsion storcd in tempdb.
An old row vcrsion in thc tempdb databasc might contain pointcrs to othcr, cvcn
oldcr vcrsions. ach row vcrsion is kcpt in thc tempdb databasc as long as thcrc arc
opcrations that might rcquirc it.
Row vcrsioning isolatcs transactions lrom thc cllccts ol modilications madc by othcr
transactions without thc nccd lor rcqucsting sharcd locks on rows that havc bccn rcad.
This signilicant rcduction in thc total numbcr ol locks acquircd by this isolation lcvcl
signilicantly incrcascs availability ol data. Howcvcr, cxclusivc locks arc still nccdcd:
transactions using thc optimistic isolation lcvcl callcd SNAPSHT rcqucst locks whcn
thcy modily rows.
Row vcrsioning is uscd, among othcr things, to
Support thc RA CMM!TT SNAPSHT isolation lcvcl
Support thc SNAPSHT isolation lcvcl
8uild thc inserted and deleted tablcs in triggcrs
Thc lollowing subscctions dcscribc thc SNAPSHT and RA CMM!TT
SNAPSHT isolation lcvcls, whilc Chaptcr 14 discusscs in dctail thc inserted and
deleted tablcs.
RAD CDMMI77D SNAPSHD7 IsoIation LeveI
RA CMM!TT SNAPSHT is a slight variation ol thc RA CMM!TT
isolation lcvcl discusscd in thc prcvious scction. !t is a statcmcntlcvcl isolation, which mcans
that any othcr transaction will rcad thc committcd valucs as thcy cxist at thc bcginning ol
thc statcmcnt. !n thc casc ol updatcs, this isolation lcvcl rcvcrts lrom row vcrsions to actual
data to sclcct rows to updatc and uscs updatc locks on thc data rows sclcctcd. Actual data
rows that havc to bc modilicd acquirc cxclusivc locks.
Thc main advantagc ol RA CMM!TT SNAPSHT is that rcad opcrations
do not block updatcs and updatcs do not block rcad opcrations. n thc othcr hand,
updatcs block othcr updatcs, bccausc cxclusivc locks arc sct bclorc an updatc opcration
is cxccutcd.
You usc thc ST clausc ol thc ALTR ATA8AS statcmcnt to cnablc thc RA
CMM!TT SNAPSHT isolation lcvcl. Altcr activation, no lurthcr changcs arc
ncccssary. Any transaction spccilicd with thc RA CMM!TT isolation lcvcl
will now run undcr RA CMM!TT SNAPSHT.
364 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
SNAPSHD7 IsoIation LeveI
Thc SNAPSHT isolation lcvcl is a transactionlcvcl isolation, which mcans that any
othcr transaction will rcad thc committcd valucs as thcy cxist just bclorc thc snapshot
transaction starts. Also, thc snapshot transaction will rcturn thc initial valuc until it
complctcs, cvcn il anothcr transaction changcd it in thc mcantimc. Thcrclorc, only altcr
thc snapshot transaction cnds will thc othcr transaction rcad a modilicd valuc.
Transactions running undcr thc SNAPSHT isolation lcvcl acquirc cxclusivc locks
on data bclorc pcrlorming thc modilication only to cnlorcc constraints. thcrwisc,
locks arc not acquircd on data until thc data is to bc modilicd. Vhcn a data row mccts
thc updatc critcria, thc snapshot transaction vcrilics that thc data row has not bccn
modilicd by a concurrcnt transaction that committcd altcr thc transaction bcgan. !l thc
data row has bccn modilicd in a concurrcnt transaction, an updatc conllict occurs and
thc snapshot transaction is tcrminatcd. Thc updatc conllict is handlcd by thc databasc
systcm and thcrc is no way to disablc thc updatc conllict dctcction.
nabling thc SNAPSHT isolation lcvcl is a twostcp proccss. First, on thc databasc
lcvcl, cnablc thc ALLV_SNAPSHT_!SLAT!N databasc option. Sccond,
lor cach scssion that will usc this isolation lcvcl, sct thc ST TRANSACT!N
!SLAT!N L\L statcmcnt to SNAPSHT. Vhcn thcsc options arc sct, vcrsions
arc built lor all rows that arc modilicd in thc databasc.
RAD COMMI77D SNAPSHO7 vs. SNAPSHO7
Thc most important dillcrcncc bctwccn thc two optimistic isolation lcvcls is that
SNAPSHT can rcsult in updatc conllicts whcn a proccss sccs thc samc data lor thc
duration ol its transaction and is not blockcd. 8y contrast, thc RA CMM!TT
SNAPSHT isolation lcvcl docs not usc its own XSN whcn choosing row vcrsions.
ach timc a statcmcnt is startcd, such a transaction rcads thc latcst XSN issucd lor that
instancc ol thc databasc systcm and sclccts thc row bascd on that numbcr.
Anothcr dillcrcncc is that thc RA CMM!TT SNAPSHT isolation
lcvcl allows othcr transactions to modily thc data bclorc thc row vcrsioning transaction
complctcs. This can lcad to a conllict il anothcr transaction modilicd thc data bctwccn thc
timc thc row vcrsioning transaction pcrlorms a rcad and subscqucntly trics to cxccutc thc
corrcsponding writc opcration. (For an application bascd on thc SNAPSHT isolation
lcvcl, thc systcm dctccts thc possiblc conllicts and scnds thc corrcsponding crror mcssagc.)
ConcIusion
Concurrcncy in multiuscr databasc systcms can lcad to scvcral ncgativc cllccts, such
as thc rcading ol noncxistcnt data or loss ol modilicd data. atabasc nginc, likc all