Sunteți pe pagina 1din 201

164 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
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

n addition to thc SLCT statcmcnt, which was introduccd in Chaptcr 6, thcrc


arc thrcc othcr ML statcmcnts: !NSRT, UPAT, and LT. Likc thc
SLCT statcmcnt, thcsc thrcc modilication statcmcnts opcratc cithcr on tablcs
or on vicws. This chaptcr discusscs thcsc statcmcnts in rclation to tablcs and givcs
cxamplcs ol thcir usc. Additionally, it cxplains two othcr statcmcnts: TRUNCAT
TA8L and MRG. Vhcrcas thc TRUNCAT TA8L statcmcnt is a Transact
SQL cxtcnsion to thc SQL standard, MRG is a ncw and standardizcd lcaturc in
SQL Scrvcr 2008. At thc cnd ol thc chaptcr thc UTPUT clausc will bc cxplaincd
and scvcral cxamplcs with thc clausc will bc shown.
INSR7 Statement
Thc !NSRT statcmcnt inscrts rows (or parts ol thcm) into a tablc. !t has two dillcrcnt
lorms:
!NSRT |!NT| tab_namc |(col_list)|
FAULT \ALUS ] \ALUS ([ FAULT ] NULL ] expression ] | ,...n| )
!NSRT !NT tab_namc ] vicw_namc |(col_list)|
[sclcct_statcmcnt ] cxccutc_statcmcnt]
Using thc lirst lorm, cxactly onc row (or part ol it) is inscrtcd into thc tab_name
tablc. Thc sccond lorm ol thc !NSRT statcmcnt inscrts thc rcsult sct lrom thc
SLCT statcmcnt or lrom thc storcd proccdurc, which is cxccutcd using thc
XCUT statcmcnt. (Thc storcd proccdurc must rcturn data, which is thcn inscrtcd
into thc tablc. Thc SLCT statcmcnt can sclcct valucs lrom a dillcrcnt tablc or
lrom thc samc tablc as thc targct ol thc !NSRT statcmcnt, as long as thc typcs ol thc
columns arc compatiblc.)
Vith both lorms, cvcry inscrtcd valuc must havc a data typc that is compatiblc with
thc data typc ol thc corrcsponding column ol thc tablc. To cnsurc compatibility, all
charactcrbascd valucs and tcmporal data must bc cncloscd in apostrophcs, whilc all
numcric valucs nccd no such cnclosing.
Inserting a SingIe Row
!n both lorms ol thc !NSRT statcmcnt, thc cxplicit spccilication ol thc column list is
optional. This mcans that omitting thc list ol columns is cquivalcnt to spccilying a list
ol all columns in thc tablc.
Thc option FAULT \ALUS inscrts dclault valucs lor all thc columns. !l a
column is ol thc data typc T!MSTAMP or has thc !NT!TY propcrty, thc valuc,
Cha pt er 7 : Modi f i c at i on of a Tabl e' s Cont ent s 201
which is automatically crcatcd by thc systcm, will bc inscrtcd. For othcr data typcs, thc
column is sct to thc appropriatc nonnull dclault valuc il a dclault cxists, or NULL, il it
docsn't. !l thc column is not nullablc, and has no FAULT valuc, thcn thc !NSRT
statcmcnt lails and an crror will bc indicatcd.
xamplcs 7.1 through 7.4 inscrt rows into thc lour tablcs ol thc sample databasc.
This action shows thc usc ol thc !NSRT statcmcnt to load a small amount ol data
into a databasc.
XAMPL 7.1
Load data into thc employee tablc:
US samplc,
!NSRT !NT cmploycc \ALUS (25348, 'Matthcw', 'Smith','d3'),
!NSRT !NT cmploycc \ALUS (10102, 'Ann', 'Joncs','d3'),
!NSRT !NT cmploycc \ALUS (18316, 'John', '8arrimorc', 'd1'),
!NSRT !NT cmploycc \ALUS (29346, 'Jamcs', 'Jamcs', 'd2'),
!NSRT !NT cmploycc \ALUS (9031, 'lsa', '8crtoni', 'd2'),
!NSRT !NT cmploycc \ALUS (2581, 'lkc', 'Hanscl', 'd2'),
!NSRT !NT cmploycc \ALUS (28559, 'Sybill', 'Moscr', 'd1'),
XAMPL 7.2
Load data into thc department tablc:
US samplc,
!NSRT !NT dcpartmcnt \ALUS ('d1', 'Rcscarch', 'allas'),
!NSRT !NT dcpartmcnt \ALUS ('d2', 'Accounting', 'Scattlc'),
!NSRT !NT dcpartmcnt \ALUS ('d3', 'Markcting', 'allas'),
XAMPL 7.3
Load data into thc project tablc:
US samplc,
!NSRT !NT projcct \ALUS ('p1', 'Apollo', 120000.00),
!NSRT !NT projcct \ALUS ('p2', 'Gcmini', 95000.00),
!NSRT !NT projcct \ALUS ('p3', 'Mcrcury', 186500.00),
202 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
XAMPL 7.4
Load data into thc works_on tablc:
US samplc,
!NSRT !NT works_on \ALUS (10102,'p1', 'Analyst', '2006.10.1'),
!NSRT !NT works_on \ALUS (10102, 'p3', 'Managcr', '2008.1.1'),
!NSRT !NT works_on \ALUS (25348, 'p2', 'Clcrk', '2007.2.15'),
!NSRT !NT works_on \ALUS (18316, 'p2', NULL, '2007.6.1'),
!NSRT !NT works_on \ALUS (29346, 'p2', NULL, '2006.12.15'),
!NSRT !NT works_on \ALUS (2581, 'p3', 'Analyst', '2007.10.15'),
!NSRT !NT works_on \ALUS (9031, 'p1', 'Managcr', '2007.4.15'),
!NSRT !NT works_on \ALUS (28559, 'p1', 'NULL', '2007.8.1'),
!NSRT !NT works_on \ALUS (28559, 'p2', 'Clcrk', '2008.2.1'),
!NSRT !NT works_on \ALUS (9031, 'p3', 'Clcrk', '2006.11.15'),
!NSRT !NT works_on \ALUS (29346, 'p1','Clcrk', '2007.1.4'),
Thcrc arc a lcw dillcrcnt ways to inscrt valucs into a ncw row. xamplcs 7.5 through
7.7 show thcsc possibilitics.
XAMPL 7.5
US samplc,
!NSRT !NT cmploycc \ALUS (15201, 'avc', 'avis', NULL),
Thc !NSRT statcmcnt in xamplc 7.5 corrcsponds to thc !NSRT statcmcnts in
xamplcs 7.1 through 7.4. Thc cxplicit usc ol thc kcyword NULL inscrts thc null valuc
into thc corrcsponding column.
Thc inscrtion ol valucs into somc (but not all) ol a tablc's columns usually rcquircs
thc cxplicit spccilication ol thc corrcsponding columns. Thc omittcd columns must
cithcr bc nullablc or havc a FAULT valuc.
XAMPL 7.6
US samplc,
!NSRT !NT cmploycc (cmp_no, cmp_lnamc, cmp_lnamc)
\ALUS (15201, 'avc', 'avis'),
xamplcs 7.5 and 7.6 arc cquivalcnt. Thc dept_no column is thc only nullablc
column in thc employee tablc bccausc all othcr columns in thc employee tablc wcrc
dcclarcd with thc NT NULL clausc in thc CRAT TA8L statcmcnt.
Cha pt er 7 : Modi f i c at i on of a Tabl e' s Cont ent s 203
Thc ordcr ol column namcs in thc \ALU clausc ol thc !NSRT statcmcnt can
bc dillcrcnt lrom thc original ordcr ol thosc columns, which is dctcrmincd in thc
CRAT TA8L statcmcnt. !n this casc, it is absolutcly ncccssary to list thc columns
in thc ncw ordcr.
XAMPL 7.7
US samplc,
!NSRT !NT cmploycc (cmp_lnamc, cmp_lnamc, dcpt_no, cmp_no)
\ALUS ('avis', 'avc', 'd1', 15201),
Inserting MuItipIe Rows
Thc sccond lorm ol thc !NSRT statcmcnt inscrts onc or morc rows sclcctcd with a
subqucry.
xamplc 7.8 shows how a sct ol rows can bc inscrtcd using thc sccond lorm ol thc
!NSRT statcmcnt.
XAMPL 7.8
Gct all thc numbcrs and namcs lor dcpartmcnts locatcd in allas, and load thc sclcctcd
data into a ncw tablc:
US samplc,
CRAT TA8L dallas_dcpt
(dcpt_no CHAR(4) NT NULL,
dcpt_namc CHAR(20) NT NULL),
!NSRT !NT dallas_dcpt (dcpt_no, dcpt_namc)
SLCT dcpt_no, dcpt_namc
FRM dcpartmcnt
VHR location - 'allas',
Thc ncw tablc crcatcd in xamplc 7.8, dallas_dept, has thc samc columns as thc
department tablc cxccpt lor thc location column. Thc subqucry in thc !NSRT
statcmcnt sclccts all rows with thc valuc 'allas' in thc location column. Thc sclcctcd
rows will bc subscqucntly inscrtcd in thc ncw tablc.
Thc contcnt ol thc dallas_dept tablc can bc sclcctcd with thc lollowing SLCT
statcmcnt:
SLCT FRM dallas_dcpt,
204 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Thc rcsult is
6ept_ae 6ept_aame
a |e.e+rc|
a1 M+r|et|a
xamplc 7.9 is anothcr cxamplc, which shows how multiplc rows can bc inscrtcd
using thc sccond lorm ol thc !NSRT statcmcnt.
XAMPL 7.9
Gct all cmploycc numbcrs, projcct numbcrs, and projcct cntcr datcs lor all clcrks who
work in projcct p2, and load thc sclcctcd data into a ncw tablc:
US samplc,
CRAT TA8L clcrk_t
(cmp_no !NT NT NULL,
projcct_no CHAR(4),
cntcr_datc AT),
!NSRT !NT clcrk_t (cmp_no, projcct_no, cntcr_datc)
SLCT cmp_no, projcct_no, cntcr_datc
FRM works_on
VHR job - 'Clcrk'
AN projcct_no - 'p2',
Thc ncw tablc, clerk_t, contains thc lollowing rows:
emp_ae pre[ect_ae eater_6ate
z!1+ jz zI-z-!
z!! jz z-z-
Thc tablcs dallas_dept and clerk_t (xamplcs 7.8 and 7.9) wcrc cmpty bclorc thc
!NSRT statcmcnt inscrtcd thc rows. !l, howcvcr, thc tablc alrcady cxists and thcrc arc
rows in it, thc ncw rows will bc appcndcd.
ca :cs /e(|c:e |c|| s|c|emes|s (t||/| /3|| cs1 ||:|| |s |scm(|e /.^ a||| ||e :|||t s|c|emes| a||| ||e
||0 :|case (see |scm(|e .+1 |s t|c(|e/ .
Cha pt er 7 : Modi f i c at i on of a Tabl e' s Cont ent s 205
7abIe VaIue Constructors and INSR7
SQL Scrvcr 2008 introduccs a ncw lcaturc callcd a table (or ro.) .alue constructor,
which allows you to assign scvcral tuplcs (rows) with a ML statcmcnt such as
!NSRT or UPAT. xamplc 7.10 shows how you can assign scvcral rows using
such a constructor with an !NSRT statcmcnt.
XAMPL 7.10
US samplc,
!NSRT !NT dcpartmcnt \ALUS ('d4', 'Human Rcsourccs', 'Chicago'),
('d5', 'istribution', 'Ncw rlcans'),
('d6', 'Salcs', 'Chicago'),
Thc !NSRT statcmcnt in xamplc 7.10 inscrts thrcc rows at thc samc timc in thc
department tablc using thc tablc valuc constructor. As you can scc lrom thc cxamplc,
thc syntax ol thc constructor is rathcr simplc. To usc a tablc valuc constructor, list thc
valucs ol cach row insidc thc pair ol brackcts and scparatc cach list lrom thc othcrs by
using a comma.
UPDA7 Statement
Thc UPAT statcmcnt modilics valucs ol tablc rows. This statcmcnt has thc gcncral
lorm:
UPAT tab_namc
[ ST column_1 - [cxprcssion ] FAULT ] NULL] |,...n|
|FRM tab_namc1 |,...n||
|VHR condition|
Rows in thc tab_name tablc arc modilicd in accordancc with thc VHR clausc.
For cach row to bc modilicd, thc UPAT statcmcnt changcs thc valucs ol thc
columns in thc ST clausc, assigning a constant (or gcncrally an cxprcssion) to thc
associatcd column. !l thc VHR clausc is omittcd, thc UPAT statcmcnt modilics
all rows ol thc tablc. (Thc FRM clausc will bc discusscd latcr in this scction.)
/s |||/| s|c|emes| :cs cs|, mc1|/, 1c|c c/ c s|s|e |c||e.
206 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
XAMPL 7.11
Sct thc task ol cmploycc numbcr 18316, who works on projcct p2, to bc 'Managcr':
US samplc,
UPAT works_on
ST job - 'Managcr'
VHR cmp_no - 18316
AN projcct_no - 'p2',
Thc UPAT statcmcnt in xamplc 7.11 modilics cxactly onc row ol thc works_on
tablc, bccausc thc combination ol thc columns emp_no and project_no builds thc
primary kcy ol that tablc and is thcrclorc uniquc. This cxamplc modilics thc task ol thc
cmploycc, which was prcviously unknown or sct to NULL.
xamplc 7.12 modilics rows ol a tablc with an cxprcssion.
XAMPL 7.12
Changc thc budgcts ol all projccts to bc rcprcscntcd in nglish pounds. Thc currcnt
ratc ol cxchangc is 0.51/ lor 81.
US samplc,
UPAT projcct
ST budgct - budgct0.51,
!n thc cxamplc, all rows ol thc project tablc will bc modilicd bccausc ol thc omittcd
VHR clausc. Thc modilicd rows ol thc project tablc can bc displaycd with thc
lollowing TransactSQL statcmcnt:
SLCT FRM projcct,
Thc rcsult is
pre[ect_ae pre[ect_aame hc6qet
j |je||e z
jz 0em|a| ++!
j1 Mercar !!
XAMPL 7.13
uc to hcr illncss, sct all tasks on all projccts lor Mrs. Joncs to NULL:
US samplc,
UPAT works_on
Cha pt er 7 : Modi f i c at i on of a Tabl e' s Cont ent s 207
ST job - NULL
VHR cmp_no !N
(SLCT cmp_no
FRM cmploycc
VHR cmp_lnamc - 'Joncs'),
xamplc 7.13 uscs an inncr qucry in thc VHR clausc ol thc UPAT statcmcnt.
8ccausc ol thc usc ol thc !N opcrator, morc than onc row can rcsult lrom this qucry.
xamplc 7.13 can also bc solvcd using thc FRM clausc ol thc UPAT statcmcnt.
Thc FRM clausc contains thc namcs ol tablcs that arc involvcd in thc UPAT
statcmcnt. All thcsc tablcs must bc subscqucntly joincd. xamplc 7.14 shows thc usc ol
thc FRM clausc. This cxamplc is idcntical to thc prcvious onc.
|e ||0/ :|case |s c /cssc:|-:9| es|ess|cs |c ||e /|:| :9| s|cs1c/1.

XAMPL 7.14
US samplc,
UPAT works_on
ST job - NULL
FRM works_on, cmploycc
VHR cmp_lnamc - 'Joncs'
AN works_on.cmp_no - cmploycc.cmp_no,
xamplc 7.15 illustratcs thc usc ol thc CAS cxprcssion in thc UPAT statcmcnt.
(For a dctailcd discussion ol this cxprcssion, rclcr to Chaptcr 6.)
XAMPL 7.15
Thc budgct ol cach projcct should bc incrcascd by a pcrccntagc (20, 10, or 5) dcpcnding
on its prcvious amount ol moncy. Thosc projccts with a lowcr budgct will bc incrcascd
by thc highcr pcrccntagcs.
US samplc,
UPAT projcct
ST budgct - CAS
VHN budgct ~0 and budgct 100000 THN budgct1.2
VHN budgct ~- 100000 and budgct 200000 THN budgct1.1
LS budgct1.05
N
208 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
DL7 Statement
Thc LT statcmcnt dclctcs rows lrom a tablc. This statcmcnt has two dillcrcnt
lorms:
LT FRM tablc_namc
|VHR prcdicatc|,
LT tablc_namc
FRM tablc_namc |,.|
|VHR condition|,
All rows that satisly thc condition in thc VHR clausc will bc dclctcd. xplicitly
naming columns within thc LT statcmcnt is not ncccssary (or allowcd), bccausc
thc LT statcmcnt opcratcs on rows and not on columns.
XAMPL 7.16
clctc all managcrs in thc works_on tablc:
US samplc,
LT FRM works_on
VHR job - 'Managcr',
Thc VHR clausc in thc LT statcmcnt can contain an inncr qucry.
XAMPL 7.17
Mrs. Moscr is on lcavc. clctc all rows in thc databasc conccrning hcr:
US samplc,
LT FRM works_on
VHR cmp_no !N
(SLCT cmp_no
FRM cmploycc
VHR cmp_lnamc - 'Moscr'),
LT FRM cmploycc
VHR cmp_lnamc - 'Moscr',
xamplc 7.17 can also bc pcrlormcd using thc FRM clausc, as xamplc 7.18
shows. This clausc has thc samc scmantics as thc FRM clausc in thc UPAT
statcmcnt.
Cha pt er 7 : Modi f i c at i on of a Tabl e' s Cont ent s 209
XAMPL 7.18
US samplc,
LT works_on
FRM works_on, cmploycc
VHR works_on.cmp_no - cmploycc.cmp_no
AN cmp_lnamc - 'Moscr',
LT FRM cmploycc
VHR cmp_lnamc - 'Moscr',
Thc usc ol thc VHR clausc in thc LT statcmcnt is optional. !l thc VHR
clausc is omittcd, all rows ol a tablc will bc dclctcd, as shown in xamplc 7.19.
XAMPL 7.19
US samplc,
LT FRM works_on,
|e/e |s c s|s|/|:cs| 1|//e/es:e |e|aees ||e ||||| cs1 ||e ||0| /3|| s|c|emes|s. |e ||||| s|c|emes|
1e|e|es ((c/||c||, c/ |c|c||, ||e :cs|es|s c/ c |c||e, a|e/ecs ||e ||0| /3|| s|c|emes| 1e|e|es |c|| ||e :cs|es|s
cs1 ||e s:|emc c/ c |c||e. |as, c/|e/ c ||||| s|c|emes|, ||e |c||e s|||| es|s|s |s ||e 1c|c|cse (c|||ca|
(css|||, a||| ce/c /cas, |a| c/|e/ c ||0| /3|| s|c|emes|, ||e |c||e sc |cse/ es|s|s.
7RUNCA7 7AL Statement
Thc TransactSQL languagc also supports thc TRUNCAT TA8L statcmcnt. This
statcmcnt normally providcs a "lastcr cxccuting" vcrsion ol thc LT statcmcnt
without thc VHR clausc. Thc TRUNCAT TA8L statcmcnt dclctcs all rows
lrom a tablc morc quickly than docs thc LT statcmcnt bccausc it drops thc
contcnts ol thc tablc pagc by pagc, whilc LT drops thc contcnts row by row.
|e |||t/| /3|| s|c|emes| |s c /cssc:|-:9| es|ess|cs |c ||e :9| s|cs1c/1.

Thc TRUNCAT TA8L statcmcnt has thc lorm:
TRUNCAT TA8L tablc_namc
210 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
|/ ,ca acs| |c 1e|e|e c|| /cas //cm c |c||e, ase ||e |||t/| /3|| s|c|emes|. ||s s|c|emes| |s s|s|/|:cs||,
/cs|e/ ||cs |||||, |e:case || |s m|s|mc||, |ce1 cs1 ||e/e c/e (as| c /ea es|/|es |s ||e |c 1a/|s ||s ese:a||cs.
(|c|s |s 1|s:asse1 |s 1e|c|| |s t|c(|e/ !?.
7be DU7PU7 CIause
Thc rcsult ol thc cxccution ol !NSRT, UPAT, or LT statcmcnts always
contains only thc tcxt conccrning thc numbcr ol modilicd rows ("3 rows dclctcd,"
lor instancc). !l thc contcnt ol such a rcsult docsn't lit your nccds, you can usc thc
UTPUT clausc, which displays cxplicitly thc rows that arc inscrtcd or updatcd in thc
tablc or dclctcd lrom it.
Thc UTPUT clausc uscs thc inserted and deleted tablcs (cxplaincd in Chaptcr 14)
to display thc corrcsponding rcsult. Also, thc UTPUT clausc must bc uscd with an
!NT cxprcssion to lill a tablc. For this rcason, you usc a tablc variablc to storc thc rcsult.
xamplc 7.20 shows how thc UTPUT statcmcnt works with a LT statcmcnt.
XAMPL 7.20
US samplc,
CLAR Cdcl_tablc TA8L (cmp_no !NT, cmp_lnamc CHAR(20)),
LT cmploycc
UTPUT LT.cmp_no, LT.cmp_lnamc !NT Cdcl_tablc
VHR cmp_no ~ 15000,
SLCT FRM Cdcl_tablc
Thc rcsult is
emp_ae emp_|aame
z!1+ :m|t|
1 |+rr|mere
z1+ I+me.
z!! Me.er
First, xamplc 7.20 dcclarcs thc tablc variablc del_table with two columns:
emp_no and emp_lname. This tablc will bc uscd to storc thc dclctcd rows. Thc syntax
ol thc LT statcmcnt is cnhanccd with thc UTPUT option:
UTPUT LT.cmp_no, LT.cmp_lnamc !NT Cdcl_tablc
Cha pt er 7 : Modi f i c at i on of a Tabl e' s Cont ent s 211
Using this option, thc systcm storcs thc dclctcd rows in thc deleted tablc, which is
thcn copicd in thc Cdel tablc variablc.
xamplc 7.21 shows thc usc ol thc UTPUT option in an UPAT statcmcnt.
XAMPL 7.21
US samplc,
CLAR Cupdatc_tablc TA8L
(cmp_no !NT, projcct_no CHAR(20),old_job CHAR(20),ncw_job CHAR(20)),
UPAT works_on
ST job - NULL
UTPUT LT.cmp_no, LT.projcct_no,
LT.job, !NSRT.job !NT Cupdatc_tablc
VHR job - 'Clcrk',
SLCT FRM Cupdatc_tablc
Thc rcsult is
emp_ae pre[ect_ae e|6_[eh aew_[eh
z!1+ jz C|er| NJ||
z!! jz C|er| NJ||
1 j1 C|er| NJ||
z1+ j C|er| NJ||
MRC Statement
SQL Scrvcr 2008 introduccs thc SQL statcmcnt callcd MRG. This statcmcnt
combincs thc scqucncc ol conditional !NSRT and UPAT commands in a singlc
atomic statcmcnt, dcpcnding on thc cxistcncc ol a rccord.
Thc main application arca lor MRG is a data warchousc cnvironmcnt (scc Part !\
ol this book), whcrc tablcs nccd to bc rclrcshcd pcriodically with ncw data arriving lrom
onlinc transaction proccssing (LTP) systcms. This ncw data may contain changcs to
cxisting rows in tablcs and/or ncw rows that nccd to bc inscrtcd. !l a row in thc ncw data
corrcsponds to an itcm that alrcady cxists in thc tablc, an UPAT statcmcnt is pcrlormcd.
thcrwisc, an !NSRT statcmcnt is pcrlormcd.
Prior to SQL Scrvcr 2008, thcsc opcrations wcrc cxprcsscd cithcr as a scqucncc ol
!NSRT and UPAT statcmcnts or as batchcs (scc Chaptcr 8), whcrc, lor cach
row, thc dccision is madc whcthcr to inscrt or updatc thc data. 8oth thcsc tcchniqucs
havc pcrlormancc disadvantagcs: thc lormcr rcquircs multiplc data scans, and thc
lattcr opcratcs on a rccordbyrccord basis. 8y cxtcnding TransactSQL with thc ncw
212 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
statcmcnt, SQL Scrvcr 2008 ovcrcomcs thc dclicicncics ol thc old approachcs and
simplilics thc implcmcntation ol data warchousing applications.
xamplcs 7.22 and 7.23 show thc usc ol thc MRG statcmcnt.
XAMPL 7.22
US samplc,
CRAT TA8L bonus
(pr_no CHAR(4),
bonus SMALL!NT FAULT 100),
!NSRT !NT bonus (pr_no) \ALUS ('p1'),
xamplc 7.22 crcatcs thc bonus tablc, which contains onc row, (p1, 100). This tablc
will bc uscd lor mcrging.
XAMPL 7.23
MRG !NT bonus 8
US!NG (SLCT projcct_no, budgct
FRM projcct)
N (8.pr_no - .projcct_no)
VHN MATCH THN
UPAT ST 8.bonus - .budgct 0.1
VHN NT MATCH THN
!NSRT (8.pr_no, 8.bonus)
\ALUS (.projcct_no, .budgct 0.05),
Thc MRG statcmcnt in xamplc 7.23 modilics thc data in thc bonus tablc
dcpcnding on thc cxisting valucs in thc pr_no column. !l a valuc lrom thc project_no
column ol thc project tablc appcars in thc pr_no column ol thc bonus tablc, thc
MATCH branch will bc cxccutcd and thc cxisting valuc will bc updatcd. thcrwisc,
thc NN MATCH branch will bc cxccutcd and thc corrcsponding !NSRT
statcmcnt inscrts ncw rows in thc bonus tablc.
Thc contcnt ol thc bonus tablc altcr thc cxccution ol thc MRG statcmcnt is as
lollows:
pr_ae heacs
j z
jz +I!
j1 1z!
Cha pt er 7 : Modi f i c at i on of a Tabl e' s Cont ent s 213
From thc rcsult sct, you can scc that a valuc ol thc bonus column rcprcscnts
10 pcrccnt ol thc original valuc in thc casc ol thc UPAT statcmcnt, and 5 pcrccnt
in thc casc ol thc !NSRT statcmcnt.
ConcIusion
Gcncrally, thcrc arc only thrcc SQL statcmcnts that can bc uscd to modily a tablc:
!NSRT, UPAT, and LT. Thcy arc gcncric in that lor all typcs ol row
inscrtion, you usc only onc statcmcnt: !NSRT. Thc samc is truc lor thc modilication ol
columns and dclction ol rows with thc UPAT and LT statcmcnts, rcspcctivcly.
Thc nonstandard statcmcnt TRUNCAT TA8L is just anothcr lorm ol thc
LT statcmcnt, but dclcting ol rows is cxccutcd lastcr with TRUNCAT
TA8L than with LT. Thc MRG statcmcnt is basically an "UPSRT"
statcmcnt: it combincs thc UPAT and thc !NSRT statcmcnts in onc statcmcnt.
Chaptcrs 5 through 7 havc introduccd all SQL statcmcnts that bclong to L
and ML. Most ol thcsc statcmcnts can bc groupcd togcthcr to build a scqucncc ol
TransactSQL statcmcnts. Such a scqucncc is thc basis lor stored procedures, which will
bc covcrcd in thc ncxt chaptcr.
xercises
.7.1
!nscrt thc data ol a ncw cmploycc callcd Julia Long, whosc cmploycc numbcr is 11111.
Hcr dcpartmcnt numbcr is not known yct.
.7.2
Crcatc a ncw tablc callcd emp_d1_d2 with all cmployccs who work lor dcpartmcnt d1
or d2, and load thc corrcsponding rows lrom thc employee tablc. Find two dillcrcnt,
but cquivalcnt, solutions.
.7.3
Crcatc a ncw tablc ol all cmployccs who cntcrcd thcir projccts in 2007 and load it with
thc corrcsponding rows lrom thc employee tablc.
.7.4
Modily thc job ol all cmployccs in projcct p1 who arc managcrs. Thcy havc to work as
clcrks lrom now on.
214 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
.7.5
Thc budgcts ol all projccts arc no longcr dctcrmincd. Assign all budgcts thc NULL
valuc.
.7.6
Modily thc jobs ol thc cmploycc with thc cmploycc numbcr 28559. From now on shc
will bc thc managcr in all hcr projccts.
.7.7
!ncrcasc thc budgct ol thc projcct whcrc thc managcr has thc cmploycc numbcr 10102.
Thc incrcasc is 10 pcrccnt.
.7.8
Changc thc namc ol thc dcpartmcnt lor which thc cmploycc namcd Jamcs works. Thc
ncw dcpartmcnt namc is Salcs.
.7.9
Changc thc cntcr datc lor thc projccts lor thosc cmployccs who work in projcct p1 and
bclong to dcpartmcnt Salcs. Thc ncw datc is 12.12.2007.
.7.10
clctc all dcpartmcnts that arc locatcd in Scattlc.
.7.11
Thc projcct p3 has bccn linishcd. clctc all inlormation conccrning this projcct in thc
samplc databasc.
.7.12
clctc thc inlormation in thc works_on tablc lor all cmployccs who work lor thc
dcpartmcnts locatcd in allas.
In 7bis Cbapter
ProceduraI xtensions
Stored Procedures
User-Defined Functions
Storcd Iroccdurcs and
!scr-Icllncd Iunctlons
Cbapter 8
Copyright 2008 by The McGraw-Hill Companies. Click here for terms of use.
216 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
T
his chaptcr introduccs batchcs and routincs. A batch is a scqucncc ol Transact
SQL statcmcnts and proccdural cxtcnsions. A routinc can bc cithcr a storcd
proccdurc or a uscrdclincd lunction (UF). Thc bcginning ol thc chaptcr
introduccs all proccdural cxtcnsions supportcd by atabasc nginc. Altcr that, proccdural
cxtcnsions arc uscd, togcthcr with TransactSQL statcmcnts, to show how batchcs can bc
implcmcntcd. A batch can bc storcd as a databasc objcct, as cithcr a storcd proccdurc or a
UF. Somc storcd proccdurcs arc writtcn by uscrs, and othcrs arc providcd by Microsolt
and arc rclcrrcd to as system stored procedures. !n contrast to uscrdclincd storcd proccdurcs,
UFs rcturn a valuc to a callcr. All routincs can bc writtcn cithcr in TransactSQL or
in anothcr programming languagc such as C# or \isual 8asic. Thc cnd ol thc chaptcr
introduccs a ncw lcaturc ol SQL Scrvcr 2008tablcvalucd paramctcrs.
ProceduraI xtensions
Thc prcccding chaptcrs introduccd TransactSQL statcmcnts that bclong to thc data
dclinition languagc and thc data manipulation languagc. Most ol thcsc statcmcnts can
bc groupcd togcthcr to build a batch. As prcviously mcntioncd, a batch is a scqucncc
ol TransactSQL statcmcnts and proccdural cxtcnsions that arc scnt to thc databasc
systcm lor cxccution togcthcr. Thc numbcr ol statcmcnts in a batch is limitcd by thc sizc
ol thc compilcd batch objcct. Thc main advantagc ol a batch ovcr a group ol singlcton
statcmcnts is that cxccuting all statcmcnts at oncc brings signilicant pcrlormancc bcnclits.
Thcrc arc a numbcr ol rcstrictions conccrning thc appcarancc ol dillcrcnt Transact
SQL statcmcnts insidc a batch. Thc most important is that thc data dclinition
statcmcnts CRAT \!V, CRAT PRCUR, and CRAT TR!GGR
must cach bc thc only statcmcnt in a batch.
c se(c/c|e ||| s|c|emes|s //cm cse csc||e/, ase ||e 0 s|c|emes|.

Thc lollowing scctions dcscribc cach proccdural cxtcnsion ol thc TransactSQL
languagc scparatcly.
Iock of Statements
A block allows thc building ol units with onc or morc TransactSQL statcmcnts. vcry
block bcgins with thc 8G!N statcmcnt and tcrminatcs with thc N statcmcnt, as
shown in thc lollowing cxamplc:
8G!N
statcmcnt_1
Cha pt er 8 : St or ed Pr oc edur es a nd Us er - Def i ned Punc t i ons 217
statcmcnt_2
.
N
A block can bc uscd insidc thc !F statcmcnt to allow thc cxccution ol morc than onc
statcmcnt, dcpcnding on a ccrtain condition (scc xamplc 8.1).
IF Statement
Thc TransactSQL statcmcnt !F corrcsponds to thc statcmcnt with thc samc namc
that is supportcd by almost all programming languagcs. !F cxccutcs onc TransactSQL
statcmcnt (or morc, cncloscd in a block) if a 8oolcan cxprcssion, which lollows thc
kcyword !F, cvaluatcs to truc. !l thc !F statcmcnt contains an LS statcmcnt, a sccond
group ol statcmcnts can bc cxccutcd il thc 8oolcan cxprcssion cvaluatcs to lalsc.
3e/c/e ,ca s|c/| |c ese:a|e |c|:|es, s|c/e1 (/c:e1a/es, cs1 |||s |s |||s :|c(|e/, (|ecse /e-:/ec|e ||e es||/e
sem/e 1c|c|cse.
XAMPL 8.1
US samplc,
!F (SLCT CUNT()
FRM works_on
VHR projcct_no - 'p1'
GRUP 8Y projcct_no ) ~ 3
PR!NT 'Thc numbcr ol cmployccs in thc projcct p1 is 4 or morc'
LS 8G!N
PR!NT 'Thc lollowing cmployccs work lor thc projcct p1'
SLCT cmp_lnamc, cmp_lnamc
FRM cmploycc, works_on
VHR cmploycc.cmp_no - works_on.cmp_no
AN projcct_no - 'p1'
N
xamplc 8.1 shows thc usc ol a block insidc thc !F statcmcnt. Thc 8oolcan cxprcssion
in thc !F statcmcnt,
(SLCT CUNT()
FRM works_on
VHR projcct_no - 'p1'
GRUP 8Y projcct_no) ~ 3
218 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
is cvaluatcd to truc lor thc sample databasc. Thcrclorc, thc singlc PR!NT statcmcnt in
thc !F part is cxccutcd. Noticc that this cxamplc uscs a subqucry to rcturn thc numbcr
ol rows (using thc CUNT aggrcgatc lunction) that satisly thc VHR condition
(projcct_no-'p1'). Thc rcsult ol xamplc 8.1 is
Thc numbcr ol cmployccs in thc projcct p1 is lour or morc
|e ||:| (c/| c/ ||e || s|c|emes| |s |scm(|e ?.! :cs|c|ss |ac s|c|emes|s. |||| cs1 :|||t. |e/e/c/e, ||e
||c:| a||| ||e 3||| cs1 ||| s|c|emes|s |s /ea|/e1 |c es:|cse ||e |ac s|c|emes|s. (|e |||| s|c|emes| |s
csc||e/ s|c|emes| ||c| |e|css |c (/c:e1a/c| es|ess|css, || /e|a/ss c ase/-1e/|se1 messce.
WHIL Statement
Thc VH!L statcmcnt rcpcatcdly cxccutcs onc TransactSQL statcmcnt (or morc,
cncloscd in a block) .hile thc 8oolcan cxprcssion cvaluatcs to truc. !n othcr words, il
thc cxprcssion is truc, thc statcmcnt (or block) is cxccutcd, and thcn thc cxprcssion is
cvaluatcd again to dctcrminc il thc statcmcnt (or block) should bc cxccutcd again. This
proccss rcpcats until thc cxprcssion cvaluatcs to lalsc.
A block within thc VH!L statcmcnt can optionally contain onc ol two statcmcnts
uscd to control thc cxccution ol thc statcmcnts within thc block: 8RAK or CNT!NU.
Thc 8RAK statcmcnt stops thc cxccution ol thc statcmcnts insidc thc block and starts thc
cxccution ol thc statcmcnt immcdiatcly lollowing this block. Thc CNT!NU statcmcnt
stops only thc currcnt cxccution ol thc statcmcnts in thc block and starts thc cxccution ol
thc block lrom its bcginning.
xamplc 8.2 shows thc usc ol thc VH!L statcmcnt.
XAMPL 8.2
US samplc,
VH!L (SLCT SUM(budgct)
FRM projcct) 500000
8G!N
UPAT projcct ST budgct - budgct1.1
!F (SLCT MAX(budgct)
FRM projcct) ~ 240000
8RAK
LS CNT!NU
N
!n xamplc 8.2, thc budgct ol all projccts will bc incrcascd by 10 pcrccnt until thc
sum ol budgcts is grcatcr than 8500,000. Howcvcr, thc rcpcatcd cxccution will bc
Cha pt er 8 : St or ed Pr oc edur es a nd Us er - Def i ned Punc t i ons 219
stoppcd il thc budgct ol onc ol thc projccts is grcatcr than 8240,000. Thc cxccution ol
xamplc 8.2 givcs thc lollowing output:
(3 rows allcctcd)
(3 rows allcctcd)
(3 rows allcctcd)
LocaI VariabIes
Local variablcs arc an important proccdural cxtcnsion to thc TransactSQL languagc.
Thcy arc uscd to storc valucs (ol any typc) within a batch or a routinc. Thcy arc "local"
bccausc thcy can only bc rclcrcnccd within thc samc batch in which thcy wcrc dcclarcd.
(atabasc nginc also supports global variablcs, which arc dcscribcd in Chaptcr 4.)
vcry local variablc must bc dclincd using thc CLAR statcmcnt. (For thc
syntax ol thc CLAR statcmcnt, scc xamplc 8.3.) Thc dclinition ol cach variablc
contains its namc and thc corrcsponding data typc. \ariablcs arc always rclcrcnccd in a
batch using thc prclix C. Thc assignmcnt ol a valuc to a local variablc is donc using thc
lollowing:


Thc usagc ol both statcmcnts lor a valuc assignmcnt is dcmonstratcd in xamplc 8.3.
XAMPL 8.3
US samplc,
CLAR Cavg_budgct MNY, Ccxtra_budgct MNY
ST Ccxtra_budgct - 15000
SLCT Cavg_budgct - A\G(budgct) FRM projcct
!F (SLCT budgct
FRM projcct
VHR projcct_no-'p1') Cavg_budgct
8G!N
UPAT projcct
ST budgct - budgct Ccxtra_budgct
VHR projcct_no -'p1'
PR!NT '8udgct lor p1 incrcascd by Ccxtra_budgct'
N
LS PR!NT '8udgct lor p1 unchangcd'
220 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Thc rcsult is
8udgct lor p1 incrcascd by Ccxtra_budgct
Thc batch in xamplc 8.3 calculatcs thc avcragc ol all projcct budgcts and comparcs
this valuc with thc budgct ol projcct p1. !l thc lattcr valuc is smallcr than thc calculatcd
valuc, thc budgct ol projcct p1 will bc incrcascd by thc valuc ol thc local variablc
Cextra_budget.
MisceIIaneous ProceduraI Statements
Thc proccdural cxtcnsions ol thc TransactSQL languagc also contain thc lollowing
statcmcnts:
RTURN
GT
RA!SRRR
VA!TFR
Thc RTURN statcmcnt has thc samc lunctionality insidc a batch as thc 8RAK
statcmcnt insidc VH!L. This mcans that thc RTURN statcmcnt causcs thc
cxccution ol thc batch to tcrminatc and thc lirst statcmcnt lollowing thc cnd ol thc
batch to bcgin cxccuting.
Thc GT statcmcnt branchcs to a labcl, which stands in lront ol a TransactSQL
statcmcnt within a batch. Thc RA!SRRR statcmcnt gcncratcs a uscrdclincd crror
mcssagc and scts a systcm crror llag. A uscrdclincd crror numbcr must bc grcatcr than
50000. (All crror numbcrs - 50000 arc systcm dclincd and arc rcscrvcd by atabasc
nginc.) Thc crror valucs arc storcd in thc global variablc CCRRR.
Thc VA!TFR statcmcnt dclincs cithcr thc timc intcrval (il thc LAY option
is uscd) or a spccilicd timc (il thc T!M option is uscd) that thc systcm has to wait
bclorc cxccuting thc ncxt statcmcnt in thc batch. Thc syntax ol this statcmcnt is
VA!TFR [LAY 'timc' ] T!M 'timc' ] T!MUT 'timcout' ]
Thc LAY option tclls thc databasc systcm to wait until thc spccilicd amount ol
timc has passcd. T!M spccilics a timc in onc ol thc acccptablc lormats lor tcmporal
data. (xamplc 13.5 in Chaptcr 13 shows thc usc ol thc VA!TFR statcmcnt.)
T!MUT spccilics thc amount ol timc, in milliscconds, to wait lor a mcssagc to
arrivc in thc qucuc.
Cha pt er 8 : St or ed Pr oc edur es a nd Us er - Def i ned Punc t i ons 221
HandIing vents witb 7RY and CA7CH Statements
\crsions ol SQL Scrvcr prcvious to SQL Scrvcr 2005 rcquirc crror handling codc altcr
cvcry TransactSQL statcmcnt that might producc an crror. (You can handlc crrors
using thc CCRRR global variablc. xamplc 13.1 in Chaptcr 13 shows thc usc ol
this variablc.) Starting with SQL Scrvcr 2005, you can capturc and handlc cxccptions
using two statcmcnts, TRY and CATCH. This scction lirst cxplains what "cxccption"
mcans and thcn discusscs how thcsc two statcmcnts work.
An cxccption is a problcm (usually an crror) that prcvcnts thc continuation ol
a program. Vith such a problcm you cannot continuc proccssing, bccausc thcrc is
not cnough inlormation nccdcd to handlc thc problcm. For this rcason, thc cxisting
problcm will bc rclcgatcd to anothcr part ol thc program, which will handlc thc
cxccption.
Thc rolc ol thc TRY statcmcnt is to capturc thc cxccption. (8ccausc this proccss
usually compriscs scvcral statcmcnts, thc tcrm "TRY block" typically is uscd instcad ol
"TRY statcmcnt.") !l an cxccption occurs within thc TRY block, thc part ol thc systcm
callcd thc cxccption handlcr dclivcrs thc cxccption to thc othcr part ol thc program,
which will handlc thc cxccption. This program part is dcnotcd by thc kcyword CATCH
and is thcrclorc callcd thc CATCH block.
|s:e(||cs |cs1||s as|s ||e | cs1 t/t| s|c|emes|s |s ||e :cmmcs ac, ||c| mc1e/s (/c/cmm|s
|csaces |||e tt cs1 |c|c |/ec| e//c/s.
xccption handling with thc TRY and CATCH blocks givcs a programmcr a lot ol
bcnclits, such as:
xccptions providc a clcan way to chcck lor crrors without cluttcring codc.
xccptions providc a mcchanism to signal crrors dircctly rathcr than using somc
xccptions can bc sccn by thc programmcr and chcckcd during thc compilations
proccss.
xamplc 8.4 shows how cxccption handling with thc TRY/CATCH works. !t shows
how you can usc cxccption handling to inscrt all statcmcnts in a batch or to roll back
thc cntirc statcmcnt group il an crror occurs. Thc cxamplc is bascd on thc rclcrcntial
intcgrity bctwccn thc department and employee tablcs. For this rcason, you havc to
crcatc both tablcs using thc PR!MARY KY and FR!GN KY constraints, as
donc in xamplc 5.11 in Chaptcr 5.
222 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
XAMPL 8.4
US samplc,
8G!N TRY
8G!N TRANSACT!N
inscrt into cmploycc valucs(11111, 'Ann', 'Smith','d2'),
inscrt into cmploycc valucs(22222, 'Matthcw', 'Joncs','d4'), rclcrcntial intcgrity crror
inscrt into cmploycc valucs(33333, 'John', '8arrimorc', 'd2'),
CMM!T TRANSACT!N
PR!NT 'Transaction committcd'
N TRY
8G!N CATCH
RLL8ACK
PR!NT 'Transaction rollcd back'
N CATCH
Altcr thc cxccution ol thc batch in xamplc 8.4, all thrcc statcmcnts in thc batch
won't bc cxccutcd at all, and thc output ol this cxamplc is
Transaction rollcd back
Thc cxccution ol xamplc 8.4 works as lollows. Thc lirst !NSRT statcmcnt is
cxccutcd succcsslully. Thcn, thc sccond statcmcnt causcs thc rclcrcntial intcgrity crror.
8ccausc all thrcc statcmcnts arc writtcn insidc thc TRY block, thc cxccption is "thrown"
and thc cxccption handlcr starts thc CATCH block. CATCH rolls back all statcmcnts
and prints thc corrcsponding mcssagc. For this rcason, thc contcnt ol thc employee
tablc won't changc.
|e s|c|emes|s 3||| |/|:/t|0|, t0//| |/|:/t|0|, cs1 |0||3/t| c/e /cssc:|-:9| s|c|emes|s
:cs:e/s|s |/cssc:||css. |ese s|c|emes|s s|c/|, :cmm||, cs1 /c|| |c:| |/cssc:||css, /es(e:|||e|,. :ee t|c(|e/ !?
/c/ ||e 1|s:ass|cs c/ ||ese s|c|emes|s cs1 |/cssc:||css ese/c||,.
Stored Procedures
A stored procedure is a spccial kind ol batch writtcn in TransactSQL, using thc SQL
languagc and its proccdural cxtcnsions. Thc main dillcrcncc bctwccn a batch and a
storcd proccdurc is that thc lattcr is storcd as a databasc objcct. !n othcr words, storcd
proccdurcs arc savcd on thc scrvcr sidc to improvc thc pcrlormancc and consistcncy ol
rcpctitivc tasks.
Cha pt er 8 : St or ed Pr oc edur es a nd Us er - Def i ned Punc t i ons 223
atabasc nginc supports storcd proccdurcs and systcm proccdurcs. Storcd
proccdurcs arc crcatcd in thc samc way as all othcr databasc objcctsthat is, by using
thc L. Systcm proccdurcs arc providcd with atabasc nginc and can bc uscd to
acccss and modily thc inlormation in thc systcm catalog. This scction dcscribcs (uscr
dclincd) storcd proccdurcs, whilc systcm proccdurcs arc cxplaincd in dillcrcnt chaptcrs
ol thc book (scc, lor cxamplc, Chaptcrs 14 and 21).
Vhcn a storcd proccdurc is crcatcd, an optional list ol paramctcrs can bc dclincd.
Thc proccdurc acccpts thc corrcsponding argumcnts cach timc it is invokcd. Storcd
proccdurcs can optionally rcturn a valuc, which displays thc uscrdclincd inlormation
or, in thc casc ol an crror, thc corrcsponding crror mcssagc.
A storcd proccdurc is prccompilcd bclorc it is storcd as an objcct in thc databasc. Thc
prccompilcd lorm is storcd in thc databasc and uscd whcncvcr thc storcd proccdurc is
cxccutcd. This propcrty ol storcd proccdurcs ollcrs an important bcnclit: thc rcpcatcd
compilation ol a proccdurc is (almost always) climinatcd, and thc cxccution pcrlormancc
is thcrclorc incrcascd. This propcrty ol storcd proccdurcs ollcrs anothcr bcnclit conccrning
thc volumc ol data that must bc scnt to and lrom thc databasc systcm. !t might takc lcss
than 50 bytcs to call a storcd proccdurc containing scvcral thousand bytcs ol statcmcnts.
Thc accumulatcd cllcct ol this savings whcn multiplc uscrs arc pcrlorming rcpctitivc tasks
can bc quitc signilicant.
Storcd proccdurcs can also bc uscd lor thc lollowing purposcs:
To control acccss authorization
To crcatc an audit trail ol activitics in databasc tablcs
Thc usc ol storcd proccdurcs providcs sccurity control abovc and bcyond thc usc ol
thc GRANT and R\K statcmcnts (scc Chaptcr 12), which dclinc dillcrcnt acccss
privilcgcs lor a uscr. This is bccausc thc authorization to cxccutc a storcd proccdurc
is indcpcndcnt ol thc authorization to modily thc objccts that thc storcd proccdurc
contains, as dcscribcd in thc ncxt scction.
Storcd proccdurcs that audit writc and/or rcad opcrations conccrning a tablc arc
an additional sccurity lcaturc ol thc databasc. Vith thc usc ol such proccdurcs, thc
databasc administrator can track modilications madc by uscrs or application programs.
Creation and xecution of Stored Procedures
Storcd proccdurcs arc crcatcd with thc CRAT PRCUR statcmcnt, which
has thc lollowing syntax:
CRAT PRC|UR| |schcma_namc.|proc_namc
|([Cparam1] typc1 | \ARY!NG| |- dclault1| |UTPUT|)| [, .]
224 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
|V!TH [RCMP!L ] NCRYPT!N ] XCUT AS 'uscr_namc']|
|FR RPL!CAT!N|
AS batch ] XTRNAL NAM mcthod_namc
schema_name is thc namc ol thc schcma to which thc owncrship ol thc crcatcd storcd
proccdurc is assigncd. proc_name is thc namc ol thc ncw storcd proccdurc.
param1 is a paramctcr, whilc type1 spccilics its data typc. Thc paramctcr in a storcd
proccdurc has thc samc logical mcaning as thc local variablc lor a batch. Paramctcrs
arc valucs passcd lrom thc callcr ol thc storcd proccdurc and arc uscd within thc storcd
proccdurc. default1 spccilics thc optional dclault valuc ol thc corrcsponding paramctcr.
(clault can also bc NULL.)
Thc UTPUT option indicatcs that thc paramctcr is a rcturn paramctcr and can bc
rcturncd to thc calling proccdurc or to thc systcm (scc xamplc 8.8).
As you alrcady know, thc prccompilcd lorm ol a proccdurc is storcd in thc databasc and
uscd whcncvcr thc storcd proccdurc is cxccutcd. !l you want to gcncratc thc prccompilcd
lorm cach timc thc proccdurc is cxccutcd, usc thc V!TH RCMP!L option.
|e ase c/ ||e || ||t0/|||| c(||cs 1es|/c,s cse c/ ||e mcs| |m(c/|cs| |ese/||s c/ ||e s|c/e1 (/c:e1a/es.
||e (e//c/mcs:e c1|cs|ce c|se1 |, c s|s|e (/e:cm(||c||cs. |c/ |||s /ecscs, ||e || ||t0/|||| c(||cs
s|ca|1 |e ase1 cs|, a|es 1c|c|cse c|(e:|s ase1 |, ||e s|c/e1 (/c:e1a/e c/e mc1|/|e1 //eaes||, c/ a|es ||e
(c/cme|e/s ase1 |, ||e s|c/e1 (/c:e1a/e c/e |c|c|||e.
Thc XCUT AS clausc spccilics thc sccurity contcxt undcr which to cxccutc thc
storcd proccdurc altcr it is acccsscd. 8y spccilying thc contcxt in which thc proccdurc
is cxccutcd, you can control which uscr account thc databasc cnginc uscs to validatc
pcrmissions on objccts rclcrcnccd by thc proccdurc.
8y dclault, only thc mcmbcrs ol thc sysadmin lixcd scrvcr rolc, and thc db_owner
and db_ddladmin lixcd databasc rolcs, can usc thc CRAT PRCUR
statcmcnt. Howcvcr, thc mcmbcrs ol thcsc rolcs may assign this privilcgc to othcr uscrs
by using thc GRANT CRAT PRCUR statcmcnt. (For thc discussion ol uscr
pcrmissions, lixcd scrvcr rolcs, and lixcd databasc rolcs, scc Chaptcr 12.)
xamplc 8.5 shows thc crcation ol thc simplc storcd proccdurc lor thc project tablc.
XAMPL 8.5
US samplc,
G
CRAT PRCUR incrcasc_budgct (Cpcrccnt !NT-5)
AS UPAT projcct
ST budgct - budgct budgctCpcrccnt/100,
Cha pt er 8 : St or ed Pr oc edur es a nd Us er - Def i ned Punc t i ons 225
|e 0 s|c|emes| |s ase1 |c se(c/c|e |ac |c|:|es. (|e t||/| ||0t||||| s|c|emes| mas| |e ||e /|/s|
s|c|emes| |s ||e |c|:|.
Thc storcd proccdurc increase_budget incrcascs thc budgcts ol all projccts lor a
ccrtain pcrccntagc valuc that is dclincd using thc paramctcr percent. Thc proccdurc
also dclincs thc dclault valuc (5), which is uscd il thcrc is no argumcnt at thc cxccution
timc ol thc proccdurc.
|| |s (css|||e |c :/ec|e s|c/e1 (/c:e1a/es ||c| /e/e/es:e scses|s|es| |c||es. ||s /ec|a/e c||cas ,ca |c 1e|a
(/c:e1a/e :c1e a|||ca| :/ec||s ||e as1e/|,|s |c||es /|/s|, c/ e|es :csse:||s |c ||e |c/e| se/|e/.
!n contrast to "basc" storcd proccdurcs that arc placcd in thc currcnt databasc, it is
possiblc to crcatc tcmporary storcd proccdurcs that arc always placcd in thc tcmporary
systcm databasc callcd tempdb. You might crcatc a tcmporary storcd proccdurc to
avoid cxccuting a particular group ol statcmcnts rcpcatcdly within a conncction. You
can crcatc local or global tcmporary proccdurcs by prcccding thc proccdurc namc with
a singlc pound sign (#proc_name) lor local tcmporary proccdurcs and a doublc pound
sign (##proc_name, lor cxamplc) lor global tcmporary proccdurcs. A local tcmporary
storcd proccdurc can bc cxccutcd only by thc uscr who crcatcd it, and only during thc
samc conncction. A global tcmporary proccdurc can bc cxccutcd by all uscrs, but only
until thc last conncction cxccuting it (usually thc crcator's) cnds.
Thc lilc cyclc ol a storcd proccdurc has two phascs: its crcation and its cxccution.
ach proccdurc is crcatcd oncc and cxccutcd many timcs. Thc XCUT statcmcnt
cxccutcs an cxisting proccdurc. Thc cxccution ol a storcd proccdurc is allowcd lor cach
uscr who cithcr is thc owncr ol or has thc XCUT privilcgc lor thc proccdurc (scc
Chaptcr 12). Thc XCUT statcmcnt has thc lollowing syntax:
||XC|UT|| |Crcturn_status -| [proc_namc
] Cproc_namc_var]
[||Cparamctcr1 -| valuc ] |Cparamctcr1-| Cvariablc |UTPUT|| ] FAULT]..
|V!TH RCMP!L|
All options in thc XCUT statcmcnt, othcr than return_status, havc thc cquivalcnt
logical mcaning as thc options with thc samc namcs in thc CRAT PRCUR
statcmcnt. return_status is an optional intcgcr variablc that storcs thc rcturn status ol a
proccdurc. Thc valuc ol a paramctcr can bc assigncd using cithcr a valuc (value) or a local
226 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
variablc (variable). Thc ordcr ol paramctcr valucs is not rclcvant il thcy arc namcd,
but il thcy arc not namcd, paramctcr valucs must bc supplicd in thc ordcr dclincd in thc
CRAT PRCUR statcmcnt.
Thc FAULT clausc supplics thc dclault valuc ol thc paramctcr as dclincd in
thc proccdurc. Vhcn thc proccdurc cxpccts a valuc lor a paramctcr that docs not havc
a dclincd dclault and cithcr a paramctcr is missing or thc FAULT kcyword is
spccilicd, an crror occurs.
|es ||e |/|t|| s|c|emes| |s ||e /|/s| s|c|emes| |s c |c|:|, ||e ac/1 |/|t|| :cs |e cm|||e1 //cm ||e
s|c|emes|. |es(||e |||s, || aca|1 |e sc/e/ |c |s:|a1e |||s ac/1 |s e|e/, |c|:| ,ca a/||e.
xamplc 8.6 shows thc usc ol thc XCUT statcmcnt.
XAMPL 8.6
US samplc,
XCUT incrcasc_budgct 10,
Thc XCUT statcmcnt in xamplc 8.6 cxccutcs thc storcd proccdurc increase_
budget (xamplc 8.5) and incrcascs thc budgcts ol all projccts by 10 pcrccnt cach.
xamplc 8.7 shows thc crcation ol a proccdurc that rclcrcnccs thc tablcs employee
and works_on.
XAMPL 8.7
US samplc,
G
CRAT PRCUR modily_cmpno (Cold_no !NTGR, Cncw_no !NTGR)
AS UPAT cmploycc
ST cmp_no - Cncw_no
VHR cmp_no - Cold_no
UPAT works_on
ST cmp_no - Cncw_no
VHR cmp_no - Cold_no
Thc proccdurc modify_empno in xamplc 8.7 dcmonstratcs thc usc ol storcd proccdurcs
as part ol thc maintcnancc ol thc rclcrcntial intcgrity (in this casc, bctwccn thc employee
and works_on tablcs). Such a storcd proccdurc can bc uscd insidc thc dclinition ol a triggcr,
which actually maintains thc rclcrcntial intcgrity (scc xamplc 14.3).
xamplc 8.8 shows thc usc ol thc UTPUT clausc.
Cha pt er 8 : St or ed Pr oc edur es a nd Us er - Def i ned Punc t i ons 227
XAMPL 8.8
US samplc,
G
CRAT PRCUR dclctc_cmp Ccmploycc_no !NT, Ccountcr !NT UTPUT
AS SLCT Ccountcr - CUNT()
FRM works_on
VHR cmp_no - Ccmploycc_no
LT FRM cmploycc
VHR cmp_no - Ccmploycc_no
LT FRM works_on
VHR cmp_no - Ccmploycc_no
This storcd proccdurc can bc cxccutcd using thc lollowing statcmcnts:
CLAR Cquantity !NT
XCUT dclctc_cmp Ccmploycc_no-28559, Ccountcr-Cquantity UTPUT
Thc prcccding cxamplc contains thc crcation ol thc delete_emp proccdurc as wcll as
its cxccution. This proccdurc calculatcs thc numbcr ol projccts on which thc cmploycc
(with thc cmploycc numbcr employee_no) works. Thc calculatcd valuc is thcn
assigncd to thc counter paramctcr. Altcr thc dclction ol all rows with thc assigncd
cmploycc numbcr lrom thc employee and works_on tablcs, thc calculatcd valuc will bc
assigncd to thc quantity variablc.
|e |c|ae c/ ||e (c/cme|e/ a||| |e /e|a/se1 |c ||e :c|||s (/c:e1a/e |/ ||e 0||| c(||cs |s ase1. |s |scm(|e ?.?,
||e 4e/ete_em (/c:e1a/e (csses ||e ceaatet (c/cme|e/ |c ||e :c|||s s|c|emes|, sc ||e (/c:e1a/e /e|a/ss
||e |c|ae |c ||e s,s|em. |e/e/c/e, ||e ceaatet (c/cme|e/ mas| |e 1e:|c/e1 a||| ||e 0||| c(||cs |s ||e
(/c:e1a/e cs ae|| cs |s ||e |/|t|| s|c|emes|.
Changing the Structure of Stored Procedures
atabasc nginc also supports thc ALTR PRCUR statcmcnt, which modilics
thc structurc ol a storcd proccdurc. Thc ALTR PRCUR statcmcnt is usually
uscd to modily TransactSQL statcmcnts insidc a proccdurc. All options ol thc ALTR
PRCUR statcmcnt corrcspond to thc options with thc samc namc in thc
CRAT PRCUR statcmcnt. Thc main purposc ol this statcmcnt is to avoid
rcassignmcnt ol cxisting privilcgcs lor thc storcd proccdurc.
228 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
|c|c|cse |s|se sa((c/|s ||e t||:0| 1c|c |,(e. ca ase |||s 1c|c |,(e |c 1e:|c/e :a/sc/s |ss|1e c s|c/e1
(/c:e1a/e. / car.er |s c (/c/cmm|s :css|/a:| ||c| |s ase1 |c s|c/e ||e ca|(a| c/ c ae/, (asac||, c se| c/ /cas
cs1 |c c||ca es1-ase/ c((||:c||css |c 1|s(|c, ||e /cas /e:c/1 |, /e:c/1. / 1e|c||e1 1|s:ass|cs c/ :a/sc/s |s ca| c/
||e s:c(e c/ |||s |cc|.
A storcd proccdurc (or a group ol storcd proccdurcs with thc samc namc) is rcmovcd
using thc RP PRCUR statcmcnt. nly thc owncr ol thc storcd proccdurc
and thc mcmbcrs ol thc db_owner and sysadmin lixcd rolcs can rcmovc thc proccdurc.
atabasc nginc contains scvcral catalog vicws in rclation to storcd proccdurcs. Thc
most important vicws arc sys.objects and sys.procedures. All rows ol sys.objects in
which thc valuc ol thc type column is cqual to P arc rclatcd to storcd proccdurcs. Thc
sys.procedures vicw inhcrits scvcral columns ol sys.objects and contains additional
inlormation conccrning thcir autocxccution.
Stored Procedures and CLR
!n thc vcrsions prcvious to SQL Scrvcr 2005, you can usc only TransactSQL statcmcnts
to crcatc storcd proccdurcs. SQL Scrvcr 2005 introduccd a ncw lcaturc, Common
Languagc Runtimc (CLR), that allows you to dcvclop dillcrcnt databasc objccts (storcd
proccdurcs, uscrdclincd lunctions, triggcrs, uscrdclincd aggrcgatcs, and uscrdclincd
typcs) using C# and \isual 8asic. CLR also allows you to cxccutc thcsc databasc objccts
using thc common runtimc systcm.
ca esc||e cs1 1|sc||e ||e ase c/ t|| ||/ca| ||e c/t_eaee/e4 c(||cs c/ ||e s_ceal/qate s,s|em (/c:e1a/e.
|se:a|e ||e ||t0|||||| s|c|emes| |c a(1c|e ||e /ass|s :cs/|a/c||cs |c|ae.
xamplc 8.9 shows how you can cnablc thc usc ol CLR.
XAMPL 8.9
US samplc,
XC sp_conligurc 'clr_cnablcd',1
RCNF!GUR
To implcmcnt, compilc, and storc proccdurcs using CLR, you havc to cxccutc thc
lollowing lour stcps in thc givcn ordcr:
1. !mplcmcnt a storcd proccdurc using C# (or \isual 8asic) and compilc thc
program, using thc corrcsponding compilcr.
Cha pt er 8 : St or ed Pr oc edur es a nd Us er - Def i ned Punc t i ons 229
2. Usc thc CRAT ASSM8LY statcmcnt to crcatc thc corrcsponding
cxccutablc lilc.
3. Storc thc proccdurc as a scrvcr objcct using thc CRAT PRCUR
statcmcnt.
4. xccutc thc proccdurc using thc XCUT statcmcnt.
/|:/csc/| saes|s as|s /cssc:|-:9| cs ||e 1e/ca|| |csace /c/ :/ec||s se/|e/-s|1e c|(e:|s.

Figurc 81 shows how CLR works. You usc a dcvclopmcnt cnvironmcnt such as
\isual Studio to implcmcnt your program. Altcr thc implcmcntation, start thc C# or
\isual 8asic compilcr to gcncratc thc objcct codc. This codc will bc storcd in a .dll lilc,
which is thc sourcc lor thc CRAT ASSM8LY statcmcnt. Altcr thc cxccution ol
this statcmcnt, you gct thc intcrmcdiatc codc. !n thc ncxt stcp you usc thc CRAT
PRCUR statcmcnt to storc thc cxccutablc as a databasc objcct. Finally, thc
storcd proccdurc can bc cxccutcd using thc alrcadyintroduccd XCUT statcmcnt.
xamplcs 8.10 through 8.14 dcmonstratc thc wholc proccss just dcscribcd.
xamplc 8.10 shows thc C# program that will bc uscd to dcmonstratc how you apply
CLR to implcmcnt and dcploy storcd proccdurcs.
Executable code
Procedure as
database object
Object code
Source code
CLR compiler
CREATE
ASSEMBLY
statement
CREATE
PROCEDURE
statement
||qcre 8-1 |e /|ca 1|c/cm /c/ ||e ese:a||cs c/ c t|| s|c/e1 (/c:e1a/e
230 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
XAMPL 8.10
using Systcm,
using Systcm.ata,
using Systcm.ata.Sql,
using Systcm.ata.SqlClicnt,
using Microsolt.SqlScrvcr.Scrvcr,
using Systcm.ata.SqlTypcs,
public partial class StorcdProccdurcs
[ |SqlProccdurc|
public static int GctmployccCount()
[
int iRows,
SqlConncction conn - ncw SqlConncction("Contcxt Conncction-truc"),
conn.pcn(),
SqlCommand sqlCmd - conn.CrcatcCommand(),
sqlCmd.CommandTcxt - "sclcct count() as 'mploycc Count' " "lrom cmploycc",
iRows - (int)sqlCmd.xccutcScalar(),
conn.Closc(),
rcturn iRows,
]
],
This program uscs a qucry to calculatc thc numbcr ol rows in thc employee tablc.
Thc using dircctivcs at thc bcginning ol thc program spccily namcspaccs, such as
System.Data. Thcsc dircctivcs allow you to spccily class namcs in thc sourcc program
without rclcrcncing thc corrcsponding namcspacc. Thc StoredProcedures class is
thcn dclincd, which is writtcn with a |SqlProcedure| attributc. This attributc tclls thc
compilcr that thc class is a storcd proccdurc. !nsidc that class is dclincd a mcthod callcd
GetEmployeeCount(). Thc conncction to thc databasc systcm is cstablishcd using thc
conn instancc ol thc SQLConnection class. Thc Open() mcthod is applicd to that
instancc to opcn thc conncction. Thc CreateCommand() mcthod, applicd to conn,
allows you to acccss thc SqlCommand instancc callcd sqlCmd.
Thc lollowing lincs ol codc
sqlCmd.CommandText =
select count(*) as 'Fmploee Count' + from emploee,
iRows = (int)sqlCmd.FxecuteScalar(),
usc thc SLCT statcmcnt to lind thc numbcr ol rows in thc employee tablc and to
display thc rcsult. Thc command tcxt is spccilicd by sctting thc CommandText propcrty
ol thc SqlCmd instancc rcturncd by thc call to thc CreateCommand() mcthod.
Cha pt er 8 : St or ed Pr oc edur es a nd Us er - Def i ned Punc t i ons 231
Ncxt, thc ExecuteScalar() mcthod ol thc SqlCommand instancc is callcd. This
rcturns a scalar valuc, which is linally convcrtcd to thc int data typc and assigncd to
thc iRows variablc.
xamplc 8.11 shows thc lirst stcp in dcploying storcd proccdurcs using CLR.
XAMPL 8.11
csc /targct:library GctmployccCount.cs
/rclcrcncc:"C:\Program Filcs\Microsolt SQL Scrvcr\MSSQL10.MSSQLSR\R\
MSSQL\8inn\sqlacccss.dll"
xamplc 8.11 dcmonstratcs how to compilc thc C# mcthod callcd GetEmployeeCount
(xamplc 8.10). (Actually, this command can bc uscd gcncrally to compilc any C# program,
il you sct thc appropriatc namc lor thc sourcc program.) csc is thc command that is uscd
to invokc thc C# compilcr. You invokc thc csc command at thc Vindows command linc.
8clorc starting thc command, you havc to spccily thc location ol thc compilcr using thc
PATH cnvironmcnt variablc. At thc timc ol writing this book, thc C# compilcr (thc csc
.exe lilc) can bc lound in thc C:\V!NVS\Microsolt.NT\Framcwork\v2.050727
dircctory. (You should sclcct thc appropriatc vcrsion ol thc compilcr.)
Thc /target option spccilics thc namc ol thc C# program, whilc thc /reference
option dclincs thc .dll lilc, which is ncccssary lor thc compilation proccss.
xamplc 8.12 shows thc ncxt stcp in crcating thc storcd proccdurc. (Usc SQL Scrvcr
Managcmcnt Studio to cxccutc this statcmcnt.)
XAMPL 8.12
US samplc,
G
CRAT ASSM8LY GctmployccCount
FRM 'C:\GctmployccCount.dll' V!TH PRM!SS!N_ST - SAF
Thc CRAT ASSM8LY statcmcnt uscs thc managcd codc as thc sourcc to
crcatc thc corrcsponding objcct, against which CLR storcd proccdurcs, UFs, and
triggcrs can bc crcatcd. This statcmcnt has thc lollowing syntax:
CRAT ASSM8LY asscmbly_namc | AUTHR!ZAT!N owncr_namc |
FRM [ dll_lilc]
|V!TH PRM!SS!N_ST - [ SAF ] XTRNAL_ACCSS ] UNSAF ]|
assembly_name is thc namc ol thc asscmbly. Thc optional AUTHR!ZAT!N
clausc spccilics thc namc ol a rolc as owncr ol thc asscmbly. Thc FRM clausc
spccilics thc path whcrc thc asscmbly bcing uploadcd is locatcd. (xamplc 8.12 copicd
232 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
thc .dll lilc gcncratcd lrom thc sourcc program lrom thc Iramework dircctory to thc
root ol thc C: drivc.)
Thc V!TH PRM!SS!N ST clausc is a vcry important clausc ol thc CRAT
ASSM8LY statcmcnt and should always bc sct. !t spccilics a sct ol codc acccss
pcrmissions grantcd to thc asscmbly. SAF is thc most rcstrictivc pcrmission sct. Codc
cxccutcd by an asscmbly with this pcrmission cannot acccss cxtcrnal systcm rcsourccs,
such as lilcs. XTRNAL_ACCSS allows asscmblics to acccss ccrtain cxtcrnal
systcm rcsourccs, whilc UNSAF allows unrcstrictcd acccss to rcsourccs, both within
and outsidc thc databasc systcm.
|s c/1e/ |c s|c/e ||e |s/c/mc||cs :cs:e/s|s cssem||, :c1e, c ase/ mas| |c|e ||e c|||||, |c ese:a|e ||e t||/|
/::|/3| s|c|emes|. |e ase/ (c/ /c|e ese:a||s ||e s|c|emes| |s ||e case/ c/ ||e cssem||,. || |s (css|||e |c
css|s cs cssem||, |c csc||e/ ase/ |, as|s ||e /||0||//|0| :|case c/ ||e t||/| :t||// s|c|emes|.
atabasc nginc also supports thc ALTR ASSM8LY and RP ASSM8LY
statcmcnts. You can usc thc ALTR ASSM8LY statcmcnt to rclrcsh thc systcm
catalog to thc latcst copy ol .NT modulcs holding its implcmcntation. This statcmcnt
also adds or rcmovcs lilcs associatcd with thc corrcsponding asscmbly. Thc RP
ASSM8LY statcmcnt rcmovcs thc spccilicd asscmbly and all its associatcd lilcs lrom
thc currcnt databasc.
xamplc 8.13 crcatcs thc storcd proccdurcs bascd on thc managcd codc implcmcntcd
in xamplc 8.10.
XAMPL 8.13
US samplc,
G
CRAT PRCUR GctmployccCount
AS XTRNAL NAM GctmployccCount.StorcdProccdurcs.GctmployccCount
Thc CRAT PRCUR statcmcnt in xamplc 8.13 is dillcrcnt lrom thc
samc statcmcnt uscd in xamplcs 8.5 and 8.7, bccausc it contains thc XTRNAL
NAM option. This option spccilics that thc codc is gcncratcd using CLR. Thc namc
in this clausc is a thrccpart namc:
assembly_name.class_name.method_name
assembly_name is thc namc ol thc asscmbly (scc xamplc 8.12).
class_name is thc namc ol thc public class (scc xamplc 8.10).
method_name
insidc thc class.
Cha pt er 8 : St or ed Pr oc edur es a nd Us er - Def i ned Punc t i ons 233
xamplc 8.14 is uscd to cxccutc thc GetEmployeeCount proccdurc.
XAMPL 8.14
US samplc,
CLAR Crct !NT
XCUT Crct-GctmployccCount
PR!NT Crct
Thc PR!NT statcmcnt rcturns thc currcnt numbcr ol thc rows in thc employee tablc.
User-Defined Functions
!n programming languagcs, thcrc arc gcncrally two typcs ol routincs:
Storcd proccdurcs

As discusscd in thc prcvious major scction ol this chaptcr, storcd proccdurcs arc
madc up ol scvcral statcmcnts that havc zcro or morc input paramctcrs but usually do
not rcturn any output paramctcrs. !n contrast, lunctions always havc onc rcturn valuc.
This scction dcscribcs thc crcation and usc ol UFs.
UFs arc crcatcd with thc CRAT FUNCT!N statcmcnt, which has thc
lollowing syntax:
CRAT FUNCT!N |schcma_namc.|lunction_namc
|([Cparam ] typc |- dclault|) [,...]
RTURNS [scalar_typc ] |Cvariablc| TA8L]
|V!TH [NCRYPT!N ] SCHMA8!N!NG]
|AS| [block ] RTURN (sclcct_statcmcnt)]
schema_name is thc namc ol thc schcma to which thc owncrship ol thc crcatcd
UF is assigncd. function_name is thc namc ol thc ncw lunction. param is an
input paramctcr, whilc type spccilics its data typc. Paramctcrs arc valucs passcd lrom
thc callcr ol thc UF and arc uscd within thc lunction. default spccilics thc optional
dclault valuc ol thc corrcsponding paramctcr. (clault can also bc NULL.)
Thc RTURNS clausc dclincs a data typc ol thc valuc rcturncd by thc UF. This
data typc can bc any ol thc standard data typcs supportcd by thc databasc systcm,
234 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
including thc TA8L data typc. (Thc only standard data typcs that you cannot usc is
thc T!MSTAMP data typc.)
UFs arc cithcr scalarvalucd or tablcvalucd. A scalarvalucd lunction rcturns
an atomic (scalar) valuc. This mcans that in thc RTURNS clausc ol a scalarvalucd
lunction, you spccily onc ol thc standard data typcs. Functions arc tablcvalucd il thc
RTURNS clausc rcturns a sct ol rows (scc thc ncxt subscction).
Thc V!TH NCRYPT!N option cncrypts thc inlormation in thc systcm
catalog that contains thc tcxt ol thc CRAT FUNCT!N statcmcnt. !n that casc,
you cannot vicw thc tcxt uscd to crcatc thc lunction. (Usc this option to cnhancc thc
sccurity ol your databasc systcm.)
Thc altcrnativc clausc, V!TH SCHMA8!N!NG, binds thc UF to thc databasc
objccts that it rclcrcnccs. Any attcmpt to modily thc structurc ol thc databasc objcct
that thc lunction rclcrcnccs lails. (Thc binding ol thc lunction to thc databasc objccts it
rclcrcnccs is rcmovcd only whcn thc lunction is altcrcd, so thc SCHMA8!N!NG
option is not spccilicd anymorc.)
atabasc objccts that arc rclcrcnccd by a lunction must lullill thc lollowing conditions
il you want to usc thc SCHMA8!N!NG clausc during thc crcation ol that lunction:
All vicws and UFs rclcrcnccd by thc lunction must bc schcmabound.
All databasc objccts (tablcs, vicws, or UFs) must bc in thc samc databasc as thc
lunction.
block is thc 8G!N/N block that contains thc implcmcntation ol thc lunction.
Thc linal statcmcnt ol thc block must bc a RTURN statcmcnt with an argumcnt.
(Thc valuc ol thc argumcnt is thc valuc rcturncd by thc lunction.) !n thc body ol a
8G!N/N block, only thc lollowing statcmcnts arc allowcd:
Assignmcnt statcmcnts such as ST


SLCT statcmcnts containing SLCT lists with cxprcssions that assign to
variablcs that arc local to thc lunction
!NSRT, UPAT, and LT statcmcnts modilying variablcs ol thc
TA8L data typc that arc local to thc lunction
8y dclault, only thc mcmbcrs ol thc sysadmin lixcd scrvcr rolc and thc db_owner
and db_ddladmin lixcd databasc rolcs can usc thc CRAT FUNCT!N statcmcnt.
Cha pt er 8 : St or ed Pr oc edur es a nd Us er - Def i ned Punc t i ons 235
Howcvcr, thc mcmbcrs ol thcsc rolcs may assign this privilcgc to othcr uscrs by using
thc GRANT CRAT FUNCT!N statcmcnt (scc Chaptcr 12).
xamplc 8.15 shows thc crcation ol thc lunction callcd compute_costs.
XAMPL 8.15
This lunction computcs additional total costs that arisc
il budgcts ol projccts incrcasc
US samplc,
G
CRAT FUNCT!N computc_costs (Cpcrccnt !NT -10)
RTURNS C!MAL(16,2)
8G!N
CLAR Cadditional_costs C (14,2), Csum_budgct dcc(16,2)
SLCT Csum_budgct - SUM (budgct) FRM projcct
ST Cadditional_costs - Csum_budgct Cpcrccnt/100
RTURN Cadditional_costs
N
Thc lunction compute_costs computcs additional costs that arisc whcn all budgcts
ol projccts incrcasc. Thc only input variablc, Cpercent, spccilics thc pcrccntagc ol
incrcasc ol budgcts. Thc 8G!N/N block lirst dcclarcs two local variablcs:
Cadditional_costs and Csum_budget. Thc lunction thcn assigns to Csum_budget
thc sum ol all budgcts, using thc spccial lorm ol thc SLCT statcmcnt. Altcr that,
thc lunction computcs total additional costs and rcturns this valuc using thc RTURN
statcmcnt.
Invoking User-Defined Iunctions
ach UF can bc invokcd in TransactSQL statcmcnts, such as SLCT, !NSRT,
UPAT, or LT. To invokc a lunction, spccily thc namc ol it, lollowcd by
parcnthcscs. Vithin thc parcnthcscs, you can spccily onc or morc argumcnts. rguments
arc valucs or cxprcssions that arc passcd to thc input paramctcrs that arc dclincd
immcdiatcly altcr thc lunction namc. Vhcn you invokc a lunction, and all paramctcrs
havc no dclault valucs, you must supply argumcnt valucs lor all ol thc paramctcrs and
you must spccily thc argumcnt valucs in thc samc scqucncc in which thc paramctcrs arc
dclincd in thc CRAT FUNCT!N statcmcnt.
xamplc 8.16 shows thc usc ol thc compute_costs lunction (xamplc 8.15) in a
SLCT statcmcnt.
236 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
XAMPL 8.16
US samplc,
SLCT projcct_no, projcct_namc
FRM projcct
VHR budgct dbo.computc_costs(25)
Thc rcsult is
pre[ect_ae pre[ect_aame
jz 0em|a|
Thc SLCT statcmcnt in xamplc 8.16 displays namcs and numbcrs ol all projccts
whcrc thc budgct is lowcr than thc total additional costs ol all projccts lor a givcn pcrccntagc.
|c:| /as:||cs ase1 |s c /cssc:|-:9| s|c|emes| mas| |e s(e:|/|e1 as|s ||s |ac-(c/| scme||c| |s,
scbeme_aeme.laact/ea_aeme.
7A8L Data 7ype
As you alrcady know, lunctions arc tablcvalucd il thc RTURNS clausc rcturns
a sct ol rows. cpcnding on how thc body ol thc lunction is dclincd, tablcvalucd
lunctions can bc classilicd as inlinc or multistatcmcnt lunctions. !l thc RTURNS
clausc spccilics TA8L with no accompanying list ol columns, thc lunction is an inlinc
lunction. !nlinc lunctions rcturn thc rcsult sct ol a SLCT statcmcnt as a variablc
ol thc TA8L data typc (scc xamplc 8.17). A multistatcmcnt tablcvalucd lunction
includcs a namc lollowcd by TA8L. (Thc namc dclincs an intcrnal variablc ol thc
typc TA8L.) You can usc this variablc to inscrt rows into it and thcn rcturn thc
variablc as thc rcturn valuc ol thc lunction.
xamplc 8.17 shows a lunction that rcturns a variablc ol thc TA8L data typc.
XAMPL 8.17
US samplc,
G
CRAT FUNCT!N cmployccs_in_projcct (Cpr_numbcr CHAR(4))
RTURNS TA8L
AS RTURN (SLCT cmp_lnamc, cmp_lnamc
FRM works_on, cmploycc
VHR cmploycc.cmp_no - works_on.cmp_no
AN projcct_no - Cpr_numbcr)
Cha pt er 8 : St or ed Pr oc edur es a nd Us er - Def i ned Punc t i ons 237
Thc employees_in_project lunction is uscd to display namcs ol all cmployccs that
bclong to a particular projcct. Thc input paramctcr pr_number spccilics a projcct
numbcr. Vhilc thc lunction gcncrally rcturns a sct ol rows, thc RTURNS clausc
contains thc TA8L data typc. (Notc that thc 8G!N/N block in xamplc 8.17
must bc omittcd, whilc thc RTURN clausc contains a SLCT statcmcnt.)
xamplc 8.18 shows thc usc ol thc employees_in_project lunction.
XAMPL 8.18
US samplc,
SLCT
FRM cmployccs_in_projcct('p3')
Thc rcsult is
emp_faame emp_|aame
|aa Ieae.
||.+ |ertea|
|||e |+a.e|
7abIe-VaIued Parameters
!n all vcrsions prcvious to SQL Scrvcr 2008, it was dillicult to scnd many paramctcrs
to a routinc. !n that casc you had to usc a tcmporary tablc, inscrt thc valucs into it, and
thcn call thc routinc. Sincc SQL Scrvcr 2008, you can usc tablcvalucd paramctcrs to
simplily this task. Thcsc paramctcrs arc uscd to dclivcr a rcsult sct to thc corrcsponding
routinc.
xamplc 8.19 shows thc usc ol a tablcvalucd paramctcr.
XAMPL 8.19
CRAT TYP dcpartmcntTypc AS TA8L
(dcpt_no CHAR(4),dcpt_namc CHAR(25),location CHAR(30)),
G
CRAT TA8L #dallasTablc
(dcpt_no CHAR(4),dcpt_namc CHAR(25),location CHAR(30)),
G
CRAT PRCUR inscrtProc
Callas dcpartmcntTypc RANLY
AS ST NCUNT N
!NSRT !NT #dallasTablc (dcpt_no, dcpt_namc, location)
SLCT FRM Callas
238 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
G
CLAR Callas AS dcpartmcntTypc,
!NSRT !NT Callas( dcpt_no, dcpt_namc, location)
SLCT FRM dcpartmcnt
VHR location - 'allas'
XC inscrtProc Callas,
xamplc 8.19 lirst dclincs thc typc callcd departmentType as a tablc. This mcans
that its typc is thc TA8L data typc, so rows can bc inscrtcd in it. !n thc insertProc
proccdurc, thc CDallas variablc, which is ol thc departmentType typc, is spccilicd.
(Thc RANLY clausc spccilics that thc contcnt ol thc tablc variablc cannot bc
modilicd.) !n thc subscqucnt batch, data is addcd to thc tablc variablc, and altcr that
thc proccdurc is cxccutcd. Thc proccdurc, whcn cxccutcd, inscrts rows lrom thc tablc
variablc into thc tcmporary tablc #dallasTable. Thc contcnt ol thc tcmporary tablc is as
lollows:
6ept_ae 6ept_aame |ecat|ea
a |e.e+rc| |+||+.
a1 M+r|et|a |+||+.
Thc usc ol tablcvalucd paramctcrs givcs you thc lollowing bcnclits:

!t rcduccs thc round trips to thc scrvcr.

Thc ncxt scction shows how tablcvalucd lunction can bc uscd with thc APPLY
opcrator.
7abIe-VaIued Iunctions and APPLY
Thc APPLY opcrator can bc combincd with a tablcvalucd lunction to producc thc
rcsult, which is similar to thc rcsult sct ol a join opcration bctwccn two tablcs. Thc
lollowing two cxamplcs shows how you can usc APPLY.
XAMPL 8.20
gcncratc lunction
CRAT FUNCT!N dbo.ln_gctjob(Ccmpid AS !NT)
RTURNS TA8L AS
Cha pt er 8 : St or ed Pr oc edur es a nd Us er - Def i ned Punc t i ons 239
RTURN
SLCT job
FRM works_on
VHR cmp_no - Ccmpid
AN job !S NT NULL AN projcct_no - 'p1',
Thc fn_getjob() lunction in xamplc 8.20 rcturns sct ol rows lrom thc works_on
tablc. This rcsult sct is "joincd" in thc lollowing cxamplc with thc contcnt ol thc
employee tablc.
XAMPL 8.21
usc CRSS APPLY
SLCT .cmp_no, cmp_lnamc, cmp_lnamc, job
FRM cmploycc as
CRSS APPLY dbo.ln_gctjob(.cmp_no) AS A
usc UTR APPLY
SLCT .cmp_no, cmp_lnamc, cmp_lnamc, job
FRM cmploycc as
UTR APPLY dbo.ln_gctjob(.cmp_no) AS A
Thc rcsult is
cmp_no cmp_lnamc cmp_lnamc job
10102 Ann Joncs Analyst
29346 Jamcs Jamcs Clcrk
9031 lsa 8crtoni Managcr
28559 Sybill Moscr NULL

cmp_no cmp_lnamc cmp_lnamc job
25348 Matthcw Smith NULL
10102 Ann Joncs Analyst
18316 John 8arrimorc NULL
29346 Jamcs Jamcs Clcrk
9031 lsa 8crtoni Managcr
2581 lkc Hanscl NULL
28559 Sybill Moscr NULL
!n thc lirst qucry ol xamplc 8.21 thc rcsult sct ol thc tablcvalucd lunction
fn_getjob() is "joincd" with thc contcnt ol thc employee tablc using thc CRSS
APPLY opcrator. fn_getjob() acts as thc right input, and thc employee tablc acts as thc
240 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
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 sccond qucry is similar to thc lirst onc, but uscs UTR APPLY, which
corrcsponds to thc outcr join opcration ol two tablcs.
Changing the Structure of UDIs
Thc TransactSQL languagc also supports thc ALTR FUNCT!N statcmcnt, which
modilics thc structurc ol a UF. This statcmcnt is usually uscd to rcmovc thc schcma
binding. All options ol thc ALTR FUNCT!N statcmcnt corrcspond to thc options
with thc samc namc in thc CRAT FUNCT!N statcmcnt.
A UF is rcmovcd using thc RP FUNCT!N statcmcnt. nly thc owncr ol
thc lunction (or thc mcmbcrs ol thc db_owner and sysadmin lixcd databasc rolcs) can
rcmovc thc lunction.
Thc sys.objects catalog vicw displays thc inlormation about cxisting UFs. (Scc
thc valucs 'FN' |lor scalar lunctions|, 'FS' |lor CLR lunctions|, 'FT' |lor tablcvalucd
lunctions|, and '!F' |lor inlinc tablcvalucd lunctions| in thc type column.) Thc systcm
proccdurc sp_helptext also providcs rclcvant inlormation about UFs.
LR
Thc discussion in "Storcd Proccdurcs and CLR" carlicr in thc chaptcr is also valid lor
UFs. Thc only dillcrcncc is that you usc thc CRAT FUNCT!N statcmcnt
(instcad ol CRAT PRCUR) to storc a UF as a databasc objcct. Also,
UFs arc uscd in dillcrcnt contcxt lrom that ol storcd proccdurcs, bccausc UFs
always havc a rcturn valuc.
xamplc 8.22 shows thc C# program uscd to dcmonstratc how UFs arc compilcd
and dcploycd.
XAMPL 8.22
using Systcm,
using Systcm.ata.Sql,
using Systcm.ata.SqlTypcs,
public class budgctPcrccnt
[ privatc const lloat pcrccnt - 10,
public static Sqloublc computc8udgct(lloat budgct)
[ lloat budgctNcw,
budgctNcw - budgct pcrccnt,
rcturn budgctNcw,
]
],
Cha pt er 8 : St or ed Pr oc edur es a nd Us er - Def i ned Punc t i ons 241
Thc C# sourcc program in xamplc 8.22 shows a UF that calculatcs thc ncw
budgct ol a projcct using thc old budgct and thc pcrccntal incrcasc. (Thc dcscription ol
thc C# program is omittcd, bccausc this program is analog to thc program in xamplc
8.10.) xamplc 8.23 shows thc CRAT ASSM8LY statcmcnt, which is ncccssary
il you want to crcatc a databasc objcct.
XAMPL 8.23
US samplc,
G
CRAT ASSM8LY computc8udgct
FRM 'C:\computc8udgct.dll'
V!TH PRM!SS!N_ST - SAF
Thc CRAT FUNCT!N statcmcnt in xamplc 8.24 storcs thc computeBudget
asscmbly as thc databasc objcct, which can bc uscd subscqucntly in data manipulation
statcmcnts, such as SLCT, as shown in xamplc 8.25.
XAMPL 8.24
US samplc,
G
CRAT FUNCT!N Rcturncomputc8udgct (Cbudgct Rcal)
RTURNS FLAT
AS XTRNAL NAM computc8udgct.budgctPcrccnt.computc8udgct
XAMPL 8.25
US samplc,
SLCT dbo.Rcturncomputc8udgct (321.50)
Thc rcsult is 3215.
ca :cs (|c:e cs es|s||s ||| c| se|e/c| (|c:es |ss|1e c :|||t s|c|emes|. |scm(|e ?.! s|cas ||s ase a||| ||e
|||| :|case, |scm(|e ?.!? |s ||e ||0/ :|case, cs1 |scm(|e ?.1: |s ||e :|||t ||s|.
242 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
ConcIusion
A storcd proccdurc is a spccial kind ol batch, writtcn cithcr in thc TransactSQL
languagc or using Common Languagc Runtimc (CLR). Storcd proccdurcs arc uscd lor
thc lollowing purposcs:
To control acccss authorization
To crcatc an audit trail ol activitics in databasc tablcs

To improvc thc pcrlormancc ol rcpctitivc tasks
Uscrdclincd lunctions havc a lot in common with storcd proccdurcs. Thc main
dillcrcncc is that UFs do not support paramctcrs but rcturn a singlc data valuc, which
can also bc a tablc.
Microsolt suggcsts using TransactSQL as thc dclault languagc lor crcating scrvcr
sidc objccts. (CLR is rccommcndcd as an altcrnativc only whcn your program contains
a lot ol computation.)
Thc ncxt chaptcr discusscs systcm catalog ol atabasc nginc.
xercises
.8.1
Crcatc a batch that inscrts 3000 rows in thc employee tablc. Thc valucs ol thc emp_no
column should bc uniquc and bctwccn 1 and 3000. All valucs ol thc columns emp_
lname, emp_fname, and dept_no should bc sct to 'Janc', ' Smith', and ' d1', rcspcctivcly.
.8.2
Modily thc batch .8.1 so that thc valucs ol thc emp_no column should bc gcncratcd
randomly using thc RAN lunction. (Hint: Usc thc tcmporal systcm lunctions
ATPART and GTAT to gcncratc thc random valucs.)
In 7bis Cbapter
Introduction to tbe
System CataIog
CeneraI Interfaces
Proprietary Interfaces
Systcm Catalog
Cbapter 9
Copyright 2008 by The McGraw-Hill Companies. Click here for terms of use.
244 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
T
his chaptcr discusscs thc systcm catalog ol atabasc nginc. Thc introduction
is lollowcd by a dcscription ol thc structurc ol scvcral catalog vicws, cach ol
which allows you to rctricvc mctadata. Thc usc ol dynamic managcmcnt vicws
and dynamic managcmcnt lunctions is also covcrcd in thc lirst part ol thc chaptcr. Four
altcrnativc ways lor rctricving mctadata inlormation arc discusscd in thc sccond part:
systcm storcd proccdurcs, systcm lunctions, propcrty lunctions, and thc inlormation
schcma.
Introduction to tbe System CataIog
Thc systcm catalog consists ol tablcs dcscribing thc structurc ol objccts such as databascs,
basc tablcs, vicws, and indiccs. (Thcsc tablcs arc callcd system base tables.) atabasc nginc
lrcqucntly acccsscs thc systcm catalog lor inlormation that is csscntial lor thc systcm to
lunction propcrly.
atabasc nginc distinguishcs thc systcm basc tablcs ol thc master databasc lrom
thosc ol a particular uscrdclincd databasc. Systcm tablcs ol thc master databasc bclong
to thc systcm catalog, whilc systcm tablcs ol a particular databasc lorm thc databasc
catalog. Thcrclorc, systcm basc tablcs occur only oncc in thc cntirc systcm (il thcy
bclong cxclusivcly to thc master databasc), whilc othcrs occur oncc in cach databasc,
including thc master databasc.
!n all rclational databasc systcms, systcm basc tablcs havc thc samc logical structurc as
basc tablcs. As a rcsult, thc samc TransactSQL statcmcnts uscd to rctricvc inlormation
in thc basc tablcs can also bc uscd to rctricvc inlormation in systcm basc tablcs.
:|s:e :9| :e/|e/ 1^^:, ||e ase c/ s,s|em |cse |c||es :|cse1 s|s|/|:cs||,. ese/c||,, ||e s,s|em |cse |c||es
:cssc| |e c::esse1 1|/e:||, cs, mc/e. ,ca |c|e |c ase es|s||s |s|e//c:es |c ae/, ||e |s/c/mc||cs //cm ||e
s,s|em :c|c|c. |e cs|, ac, |c c::ess s,s|em |s/c/mc||cs //cm s,s|em |cse |c||es 1|/e:||, |s |c mc|e c
:csse:||cs as|s ||e 1e1|:c|e1 c1m|s|s|/c|c/ :csse:||cs (:ee t|c(|e/ 1.
Thcrc arc scvcral dillcrcnt intcrlaccs that you can usc to acccss thc inlormation in
thc systcm basc tablcs:
Catalog views Prcscnt thc primary intcrlacc to thc mctadata storcd in systcm
basc tablcs. (Mctadata is data that dcscribcs thc attributcs ol objccts in a databasc
systcm.)
Dynamic management views (DMVs) and functions (DMIs) Gcncrally uscd
to obscrvc activc proccsscs and thc contcnts ol thc mcmory.
Cha pt er 9 : Sys t em Cat a l og 245
nformation schema A standardizcd solution lor thc acccss ol mctadata that
givcs you a gcncral intcrlacc not only lor atabasc nginc, but lor all cxisting
rclational databasc systcms (assuming that thc systcm supports thc inlormation
schcma).
System and property functions Allow you to rctricvc systcm inlormation.
di crcncc bctwccn thcsc two lunction typcs is mainly in thcir structurc. Also,
propcrty lunctions can rcturn morc inlormation than systcm lunctions.
System procedures Somc systcm proccdurcs can bc uscd to acccss and modily
thc contcnt ol thc systcm basc tablcs.
Figurc 91 shows a simplilicd lorm ol atabasc nginc's systcm inlormation and
dillcrcnt intcrlaccs that you can usc to acccss it.
||s :|c(|e/ s|cas ,ca (as| cs c|e/||ea c/ ||e s,s|em :c|c|c cs1 ||e ac,s |s a||:| ,ca :cs c::ess me|c1c|c.
|c/||:a|c/ :c|c|c ||eas, cs ae|| cs c|| c||e/ |s|e//c:es, ||c| c/e s(e:|/|: /c/ 1|//e/es| |c(|:s (sa:| cs |s1|:es,
se:a/||,, e|:. c/e 1|s:asse1 |s ||e :c//es(cs1|s :|c(|e/s.
Thcsc intcrlaccs can bc groupcd in two groups: general intcrlaccs (catalog vicws,
M\s and MFs, and thc inlormation schcma), and proprietary intcrlaccs in rclation
to atabasc nginc (systcm proccdurcs and systcm and propcrty lunctions).
||qcre 9-1 /c(||:c| (/eses|c||cs c/ 1|//e/es| |s|e//c:es /c/ ||e s,s|em :c|c|c
246 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
ese/c| mecss ||c| c|| /e|c||csc| 1c|c|cse s,s|ems sa((c/| sa:| |s|e//c:es, |a| ase 1|//e/es| |e/m|sc|c,.
|c/ |ss|cs:e, |s 0/c:|es |e/m|sc|c,, :c|c|c ||eas cs1 |/ls c/e :c||e1 1c|c 1|:||csc/, ||eas cs1 l, ||eas,
/es(e:|||e|,.
Thc lollowing scction dcscribcs gcncral intcrlaccs. Proprictary intcrlaccs arc discusscd
latcr in thc chaptcr.
CeneraI Interfaces
As alrcady statcd, thc lollowing intcrlaccs arc gcncral intcrlaccs:
Catalog vicws
M\s and MFs
!nlormation schcma
CataIog Views
SQL Scrvcr 2005 introduccd catalog vicws as a ncw intcrlacc to rctricvc systcm inlormation
lrom thc systcm catalog. Catalog vicws arc thc most gcncral intcrlacc to thc mctadata
and providc thc most cllicicnt way to obtain customizcd lorms ol this inlormation (scc
xamplcs 9.1 through 9.3).
Catalog vicws bclong to thc sys schcma, so you havc to usc thc schcma namc whcn
you acccss onc ol objccts. This scction dcscribcs thc thrcc most important catalog vicws:
sys.objccts
sys.columns
sys.databasc_principals
ca :cs /|s1 ||e 1es:/|(||cs c/ c||e/ ||eas e|||e/ |s 1|//e/es| :|c(|e/s c/ |||s |cc| c/ |s 3cc|s 0s||se.

Thc sys.objects catalog vicw contains a row lor cach uscrdclincd objcct in rclation
to thc uscr's schcma. Thcrc arc two othcr catalog vicws that show similar inlormation:
sys.system_objects and sys.all_objects. Thc lormcr contains a row lor cach systcm
Cha pt er 9 : Sys t em Cat a l og 247
objcct, whilc thc lattcr shows thc union ol all schcmascopcd uscrdclincd objccts and
systcm objccts. (All thrcc catalog vicws havc thc samc structurc.) Tablc 91 lists and
dcscribcs thc most important columns ol thc sys.objects catalog vicw.
Thc sys.columns catalog vicw contains a row lor cach column ol an objcct that has
columns, such as tablcs and vicws. Tablc 92 lists and dcscribcs thc most important
columns ol thc sys.columns catalog vicw.
Thc sys.database_principals catalog vicw contains a row lor cach sccurity principal
(that is, uscr, group, or rolc in a databasc). (For a dctailcd discussion ol principals, scc
Chaptcr 12.) Tablc 93 lists and dcscribcs thc most important columns ol thc sys.objects
catalog vicw.
:9| :e/|e/ 1^^? s|||| sa((c/|s sc-:c||e1 :cm(c|||||||, ||eas /c/ |c:|ac/1 :cm(c|||||||, a||| :9| :e/|e/ 1^^^.
|c:| :cm(c|||||||, ||ea |cs ||e scme scme (cs1 ||e scme s|/a:|a/e cs ||e :c//es(cs1|s s,s|em |cse |c||e c/
||e :9| :e/|e/ 1^^^ s,s|em. tcm(c|||||||, ||eas c/e c 1e(/e:c|e1 /ec|a/e cs1 a||| |e /emc|e1 |s c /a|a/e |e/s|cs
c/ :9| :e/|e/.
Querying CataIog Views
As alrcady statcd in this chaptcr, all systcm tablcs havc thc samc structurc as basc tablcs.
8ccausc systcm tablcs cannot bc rclcrcnccd dircctly, you havc to qucry catalog vicws, which
corrcspond to particular systcm tablcs. xamplcs 9.1 through 9.3 usc cxisting catalog vicws
to dcmonstratc how inlormation conccrning databasc objccts can bc qucricd.
Ce|cma Name 0escr|pt|ea
a+me 0|ject a+me
e|ject_|a 0|ject |aeat|l|c+t|ea aam|er, aa|ae w|t||a + a+t+|+.e
.c|em+_|a || el t|e .c|em+ |a w||c| t|e e|ject |. ceat+|aea
tje 0|ject tje
Iah|e 9-1 :e|e:|e1 tc|amss c/ ||e s,s.c|(e:|s tc|c|c l|ea
Iah|e 9-1 :e|e:|e1 tc|amss c/ ||e s,s.:c|amss tc|c|c l|ea
Ce|cma Name 0escr|pt|ea
e|ject_|a || el t|e e|ject te w||c| t||. ce|ama |e|ea.
a+me Ce|ama a+me
ce|ama_|a || el t|e ce|ama (aa|ae w|t||a t|e e|ject}
248 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
XAMPL 9.1
Gct thc tablc !, uscr !, and tablc typc ol thc employee tablc:
US samplc,
SLCT objcct_id, principal_id, typc
FRM sys.objccts
VHR namc - 'cmploycc',
Thc rcsult is
eh[ect_|6 pr|ac|pa|_|6 tpe
!1z NJ|| J
Thc object_id column ol thc sys.objects catalog vicw displays thc uniquc !
numbcr lor thc corrcsponding databasc objcct. Thc NULL valuc in thc principal_id
column tclls that thc objcct's owncr is thc samc as thc owncr ol thc schcma. U in thc
type column stands lor thc uscr (tablc).
XAMPL 9.2
Gct thc namcs ol all tablcs ol thc sample databasc that contain thc project_no column:
US samplc,
SLCT sys.objccts.namc
FRM sys.objccts !NNR J!N sys.columns
N sys.objccts.objcct_id - sys.columns.objcct_id
VHR sys.objccts.typc - 'U'
AN sys.columns.namc - 'projcct_no',
Thc rcsult is
aame
jreject
wer|._ea
Iah|e 9-1 :e|e:|e1 tc|amss c/ ||e s,s.1c|c|cse_(/|s:|(c|s tc|c|c l|ea
Ce|cma Name 0escr|pt|ea
a+me N+me el jr|ac|j+|
jr|ac|j+|_|a || el jr|ac|j+| (aa|ae w|t||a t|e a+t+|+.e}
tje |r|ac|j+| tje
Cha pt er 9 : Sys t em Cat a l og 249
XAMPL 9.3
Vho is thc owncr ol thc employee tablc:
SLCT sys.databasc_principals.namc
FRM sys.databasc_principals !NNR J!N sys.objccts
N sys.databasc_principals.principal_id - sys.objccts.schcma_id
VHR sys.objccts.namc - 'cmploycc'
AN sys.objccts.typc - 'U',
Thc rcsult is
aame
a|e
Dynamic Management Views and Functions
ynamic managcmcnt vicws (M\s) and lunctions (MFs) rcturn scrvcr statc
inlormation that can bc uscd to obscrvc activc proccsscs and thcrclorc to tunc systcm
pcrlormancc or to monitor thc actual systcm statc. !n contrast to catalog vicws, thc
M\s and MFs arc bascd on intcrnal structurcs ol thc systcm.
|e mc|s 1|//e/es:e |e|aees :c|c|c ||eas cs1 |/ls |s |s ||e|/ c((||:c||cs. :c|c|c ||eas 1|s(|c, ||e s|c||:
|s/c/mc||cs c|ca| me|c1c, a|||e |/ls (cs1 |/|s c/e ase1 |c c::ess 1,scm|: (/c(e/||es c/ ||e s,s|em.
|s c||e/ ac/1s, ,ca ase |/ls |c e| |ss|||/a| |s/c/mc||cs c|ca| ||e 1c|c|cse, |s1|||1ac| ae/|es, c/ cs
|s1|||1ac| ase/.
M\s and MFs bclong to thc sys schcma and thcir namcs start with thc prclix
dm_, lollowcd by a tcxt string that indicatcs thc catcgory to which thc particular M\
or MF bclongs.
Thc lollowing list idcntilics and dcscribcs somc ol thcsc catcgorics:
dm_db_* Contains inlormation about databascs and thcir objccts
dm_tran_* Contains inlormation in rclation to transactions
dm_io_* Contains inlormation about !/ activitics
dm_exec_* Contains inlormation rclatcd to thc cxccution ol uscr codc
250 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
/cs, |/ls cs1 |/|s c/e 1|s:asse1 |s sa|seaes| :|c(|e/s c/ ||e |cc|. |c/ |ss|cs:e, |s1es-/e|c|e1 |/ls cs1
|/|s, a||:| |e|cs |c ||e 1|_1|_` :c|ec/,, c/e es(|c|se1 |s ||e ses| :|c(|e/, a|||e |/cssc:||cs-/e|c|e1 |/ls
cs1 |/|s c/e 1|s:asse1 |s t|c(|e/ !?.
Information Scbema
Thc inlormation schcma consists ol rcadonly vicws that providc inlormation about all
tablcs, vicws, and columns ol atabasc nginc to which you havc acccss. !n contrast
to thc systcm catalog that managcs thc mctadata applicd to thc systcm as a wholc, thc
inlormation schcma primarily managcs thc cnvironmcnt ol a databasc.
|e |s/c/mc||cs s:|emc acs c/||sc||, |s|/c1a:e1 |s ||e :9|^1 s|cs1c/1. |c|c|cse |s|se (/c||1es |s/c/mc||cs
s:|emc ||eas sc ||c| c((||:c||css 1e|e|c(e1 cs c||e/ 1c|c|cse s,s|ems :cs c||c|s ||s s,s|em :c|c|c a|||ca|
|c||s |c ase || 1|/e:||,. |ese s|cs1c/1 ||eas ase 1|//e/es| |e/m|sc|c,, sc a|es ,ca |s|e/(/e| ||e :c|ams
scmes, |e cac/e ||c| :c|c|c 1c|c|cse cs1 1cmc|s ase/-1e/|se1 1c|c |,(e.
Thc lollowing scctions providc a dcscription ol thc most important inlormation
schcma vicws.
Information_schema.tabIes
Thc nformation_schema.tables vicw contains onc row lor cach tablc in thc currcnt
databasc to which thc uscr has acccss. Thc vicw rctricvcs thc inlormation lrom thc
systcm catalog using thc sys.objects catalog vicw. Tablc 94 lists and dcscribcs thc lour
columns ol this vicw.
Ce|cma 0escr|pt|ea
I||||_C|I||00 I|e a+me el t|e c+t+|e (a+t+|+.e} te w||c| t|e .|ew |e|ea.
I||||_:C||M| I|e a+me el t|e .c|em+ te w||c| t|e .|ew |e|ea.
I||||_N|M| I|e t+||e a+me
I||||_I\|| I|e tje el t|e t+||e (c+a |e ||:| I|||| er \||\}
Iah|e 9-4 |e |s/c/mc||cs_s:|emc.|c||es l|ea
Cha pt er 9 : Sys t em Cat a l og 251
Information_schema.coIumns
Thc nformation_schema.columns vicw contains onc row lor cach column in thc
currcnt databasc acccssiblc by thc uscr. Thc vicw rctricvcs thc inlormation lrom thc
sys.columns and sys.objects catalog vicws. Tablc 95 lists and dcscribcs thc six most
important columns ol this vicw.
Information_schema.referentiaI_constraints
Thc information_schema.referentail_constraints vicw contains onc row lor cach
rclcrcntial constraint owncd by thc currcnt uscr and dclincd in thc currcnt databasc.
Tablc 96 lists and dcscribcs thc most important columns ol this vicw.
Ce|cma 0escr|pt|ea
I||||_C|I||00 I|e a+me el t|e c+t+|e (a+t+|+.e} te w||c| t|e ce|ama |e|ea.
I||||_:C||M| I|e a+me el t|e .c|em+ te w||c| t|e ce|ama |e|ea.
I||||_N|M| I|e a+me el t|e t+||e te w||c| t|e ce|ama |e|ea.
C0|JMN_N|M| I|e ce|ama a+me
0|||N||_|0:|I|0N I|e ce|ama |aeat|l|c+t|ea aam|er
||I|_I\|| I|e a+t+ tje el t|e ce|ama
Iah|e 9- |e |s/c/mc||cs_s:|emc.:c|amss l|ea
Ce|cma 0escr|pt|ea
C0N:I|||NI_C|I||00 I|e a+me el t|e c+t+|e (a+t+|+.e} te w||c| t|e relereat|+| cea.tr+|at |e|ea.
C0N:I|||NI_:C||M| I|e a+me el t|e .c|em+ te w||c| t|e relereat|+| cea.tr+|at |e|ea.
C0N:I|||NI_N|M| I|e cea.tr+|at a+me
||||I|_|J|| I|e +ct|ea t|+t |. t+|ea |l + ||||I| .t+temeat .|e|+te. relereat|+| |ater|t ael|aea |
t||. cea.tr+|at (cea|a |e N0 |CI|0N, C|:C|||, :|I NJ||, er :|I ||||J|I}
J|||I|_|J|| I|e +ct|ea t|+t |. t+|ea |l +a J|||I| .t+temeat .|e|+te. relereat|+| |ater|t ael|aea |
t||. cea.tr+|at (cea|a |e N0 |CI|0N, C|:C|||, :|I NJ||, er :|I ||||J|I}
Iah|e 9-6 |e |s/c/mc||cs_s:|emc./e/e/es||c|_:css|/c|s|s l|ea
252 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
Proprietary Interfaces
Thc prcvious scction dcscribcs thc usc ol thc gcncral intcrlaccs lor acccssing systcm
basc tablcs. You can also rctricvc systcm inlormation using onc ol thc lollowing
proprictary mcchanisms ol atabasc nginc:
Systcm storcd proccdurcs
Systcm lunctions
Propcrty lunctions
Thc lollowing scctions dcscribc thcsc intcrlaccs.
System Procedures
Systcm proccdurcs arc uscd to providc many administrativc and cnduscr tasks, such
as rcnaming databasc objccts, idcntilying uscrs, and monitoring authorization and
rcsourccs. Almost all cxisting systcm proccdurcs acccss systcm basc tablcs to rctricvc
and modily systcm inlormation.
|e mcs| |m(c/|cs| (/c(e/|, c/ s,s|em (/c:e1a/es |s ||c| ||e, :cs |e ase1 /c/ ecs, cs1 /e||c||e mc1| /|:c||cs c/
s,s|em |cse |c||es.
This scction dcscribcs two systcm proccdurcs: sp_help and sp_depends. cpcnding
on thc subjcct mattcr ol thc chaptcrs, ccrtain systcm proccdurcs wcrc discusscd in prcvious
chaptcrs, and additional proccdurcs will bc discusscd in latcr chaptcrs ol thc book.
Thc sp_help systcm proccdurc displays inlormation about onc or morc databasc
objccts. Thc namc ol any databasc objcct or data typc can bc uscd as a paramctcr ol this
proccdurc. !l sp_help is cxccutcd without any paramctcr, inlormation on all databasc
objccts ol thc currcnt databasc will bc displaycd.
Thc sp_depends systcm proccdurc displays thc dcpcndcncy inlormation among
tablcs, vicws, triggcrs, and storcd proccdurcs.
xamplc 9.4 displays thc dcpcndcncy inlormation lor thc modily_cmpno storcd
proccdurc. (This uscrdclincd proccdurc is crcatcd in Chaptcr 8, xamplc 8.7.)
XAMPL 9.4
US samplc,
XC sp_dcpcnds Cobjnamc - 'modily_cmpno',
Cha pt er 9 : Sys t em Cat a l og 253
Thc rcsult is
aame tpe cp6ate6 se|ecte6 ce|cma
a|e.wer|._ea a.er t+||e e. e. emj_ae
a|e.emj|eee a.er t+||e e. e. emj_ae
Thc sp_depends systcm proccdurc in xamplc 9.4 displays thc dcpcndcncy
inlormation ol thc modify_empno proccdurc (crcatcd in xamplc 8.7 in Chaptcr 8).
This inlormation contains thc namcs ol thc tablcs that arc rclcrcnccd in thc proccdurc
(works_on and employee).
System Functions
Systcm lunctions arc dcscribcd in Chaptcr 5. Somc ol thcm can bc uscd to acccss
systcm basc tablcs. xamplc 9.5 shows two SLCT statcmcnts that rctricvc thc samc
inlormation using dillcrcnt intcrlaccs.
XAMPL 9.5
US samplc,
SLCT objcct_id
FRM sys.objccts
VHR namc - 'cmploycc',
SLCT objcct_id('cmploycc'),
Thc sccond SLCT statcmcnt in xamplc 9.5 uscs thc systcm lunction object_id
to rctricvc thc ! ol thc employee tablc. (This inlormation can bc storcd in a variablc
and uscd whcn calling a command, or a systcm proccdurc, with thc objcct's ! as a
paramctcr.)
Thc lollowing systcm lunctions, among othcrs, acccss systcm basc tablcs:
8JCT_!(objcct_namc)
8JCT_NAM(objcct_id)
USR_!(|uscr_namc|)
USR_NAM(|uscr_id|)
8_!(|db_namc|)
8_NAM(|db_id|)
!NX_CL(tablc, indcx_id, col_id)
254 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
As xamplc 9.6 dcmonstratcs, using thc !NX_CL systcm lunction is much
casicr than rctricving thc samc inlormation using thc corrcsponding catalog vicws, lor
instancc. (Thc !NX_CL lunction displays thc namc ol thc column on which an
indcx kcy is bascd.)
XAMPL 9.6
SLCT !NX_CL('cmploycc', 1,1) AS indcx_col_1
!l thcrc is a clustcrcd indcx lor thc emp_no column ol thc employee tablc, thc rcsult
is thc lollowing:
|a6ex_ce|_1
emj_ae
xamplc 9.6 rctricvcs thc clustcrcd indcx (indcx_id - 1) ol thc lirst column (col_id - 1)
ol thc employee tablc.
Property Functions
Propcrty lunctions rcturn propcrtics ol databasc objccts, data typcs, or lilcs. Gcncrally,
propcrty lunctions can rcturn morc inlormation than systcm lunctions can rcturn,
bccausc propcrty lunctions support dozcns ol propcrtics (as paramctcrs), which you can
spccily cxplicitly.
Almost all propcrty lunctions rcturn onc ol thc lollowing thrcc valucs: 0, 1, or NULL.
!l thc valuc is 0, thc objcct docs not havc thc spccilicd propcrty. !l thc valuc is 1, thc objcct
has thc spccilicd propcrty. Similarly, thc valuc NULL spccilics that thc cxistcncc ol thc
spccilicd propcrty lor thc objcct is unknown to thc systcm.
atabasc nginc supports, among othcrs, thc lollowing propcrty lunctions:
8JCTPRPRTY(id, propcrty)
CLUMNPRPRTY(id, column, propcrty)

TYPPRPRTY(typc, propcrty)
Thc 8JCTPRPRTY lunction rcturns inlormation about objccts in thc currcnt
databasc (scc xcrcisc .9.2). Thc CLUMNPRPRTY lunction rcturns inlormation
about a column or proccdurc paramctcr. Thc F!LPRPRTY lunction rcturns
thc spccilicd lilcnamc and propcrty valuc lor a givcn lilcnamc and propcrty namc.
Cha pt er 9 : Sys t em Cat a l og 255
Thc TYPPRPRTY lunction rcturns inlormation about a data typc. (Thc
dcscription ol cxisting propcrtics lor cach propcrty lunction can bc lound in 8ooks
nlinc.) Thc usc ol scvcral propcrty lunctions will bc dcmonstratcd in dillcrcnt chaptcrs
ol this book.
ConcIusion
Thc systcm catalog is a collcction ol systcm basc tablcs bclonging to thc master databasc
and cxisting uscr databascs. Gcncrally, systcm basc tablcs cannot bc qucricd dircctly by
a uscr. atabasc nginc supports scvcral dillcrcnt intcrlaccs that you can usc to acccss
thc inlormation lrom thc systcm catalog. Catalog vicws arc thc most gcncral intcrlacc
that you can apply to obtain systcm inlormation. ynamic managcmcnt vicws (M\s)
and lunctions (MFs) arc similar to catalog vicws, but you usc thcm to acccss dynamic
propcrtics ol thc systcm. Systcm storcd proccdurcs providc casy and rcliablc acccss to
systcm basc tablcs. !t is strongly rccommcndcd to cxclusivcly usc systcm proccdurcs lor
modilication ol systcm inlormation.
Thc inlormation schcma is a collcction ol vicws dclincd on systcm basc tablcs that
providc unilicd acccss to thc systcm catalog lor all databasc applications dcvclopcd
on othcr databasc systcms. Thc usc ol thc inlormation schcma is rccommcndcd il you
intcnd to port your systcm lrom onc databasc systcm to anothcr.
Thc ncxt chaptcr introduccs you to databasc indiccs.
xercises
.9.1
Using catalog vicws, lind thc opcrating systcm path and lilcnamc ol thc sample
databasc.
.9.2
Using thc 8JCTPRPRTY propcrty lunction, lind out whcthcr thc clustcrcd
indcx lor thc employee tablc ol thc sample databasc cxists.
.9.3
Using catalog vicws, lind how many intcgrity constraints arc dclincd lor thc employee
tablc ol thc sample databasc.
256 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
.9.4
Using catalog vicws, lind out il thcrc is any intcgrity constraint dclincd lor thc dept_no
column ol thc employee tablc.
.9.5
Using thc inlormation schcma, display all uscr tablcs that bclong to thc AdventureWorks
databasc.
.9.6
Using thc inlormation schcma, lind all columns ol thc employee tablc with thcir
ordinal positions and thc corrcsponding data typcs.
In 7bis Cbapter
Introduction
7ransact-SL and Indices
CuideIines for Creating
and Using Indices
Indices on Computed
CoIumns

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 data structurc. As its namc


suggcsts, a 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 and thc dircct acccss to thc row ol


thc employee tablc with thc valuc 25348 in its emp_no column. (!t is assumcd that thc
employee tablc has an indcx on thc emp_no column.) You can also scc that cach 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 structurc to thc lcal nodcs, which


arc linkcd togcthcr in a doubly linkcd list callcd a pagc chain. Thc important propcrty ol
a clustcrcd indcx is that its lcal pagcs contain data pagcs. (All othcr lcvcls ol a clustcrcd
indcx structurc arc composcd ol indcx pagcs.) !l a clustcrcd indcx is (implicitly or
cxplicitly) dclincd lor a tablc, thc tablc is callcd a clustered table. Figurc 102 shows thc
8

trcc structurc ol a clustcrcd indcx.


A clustcrcd indcx is built by dclault lor cach tablc, lor which you dclinc thc primary
kcy using thc primary kcy constraint. Also, cach clustcrcd indcx is uniquc by dclault
that is, cach data valuc can appcar only oncc in a column lor which thc clustcrcd indcx
is dclincd. !l a clustcrcd indcx is built on a nonuniquc column, thc databasc systcm will
lorcc uniqucncss by adding a 4bytc idcntilicr to thc rows that havc duplicatc valucs.
t|as|e/e1 |s1|:es c||ca |e/, /cs| c::ess |s ||e :cse ||c| c ae/, sec/:|es /c/ c /cse c/ |c|aes (see t|c(|e/ 1^.
Cha pt er l 0: | ndi c es 261
NoncIustered Indices
A nonclustcrcd indcx has thc samc indcx structurc as a clustcrcd indcx, with two
important dillcrcnccs:
A nonclustcrcd indcx docs not changc thc physical ordcr ol thc rows in thc tablc.

Thc physical ordcr ol rows in a tablc will not bc changcd il onc or morc nonclustcrcd
indiccs arc dclincd lor that tablc. For cach nonclustcrcd indcx, atabasc nginc crcatcs
an additional indcx structurc that is storcd in indcx pagcs.
A bookmark ol a nonclustcrcd indcx shows whcrc to lind thc row corrcsponding
to thc indcx kcy. Thc bookmark part ol thc indcx kcy can havc two lorms, dcpcnding
on thc lorm ol thc tablcthat is, thc tablc can bc a clustcrcd tablc or a hcap. (!n SQL
Scrvcr tcrminology, a heap is a tablc without a clustcrcd indcx.) !l a clustcrcd indcx
cxists, thc bookmark ol thc nonclustcrcd indcx shows thc 8

trcc structurc ol thc tablc's


clustcrcd indcx. !l thc tablc has no clustcrcd indcx, thc bookmark is idcntical to thc
row idcntilicr (R!), which contains thrcc parts: thc addrcss ol thc lilc to which thc
corrcsponding tablc bclongs, thc addrcss ol thc physical block (pagc) in which thc row
is storcd, and thc ollsct, which is thc position ol thc row insidc thc pagc.
As thc prcccding discussion indicatcs, scarching lor data using a nonclustcrcd indcx
could procccd in cithcr ol two dillcrcnt ways, dcpcnding on thc lorm ol thc tablc:
Heap Travcrsal ol thc nonclustcrcd indcx structurc is lollowcd by thc rctricval ol
thc row using thc R!.
Clustered table Travcrsal ol thc nonclusturcd indcx structurc is lollowcd by
travcrsal ol thc corrcsponding clustcrcd indcx.
||qcre 1-1 ||,s|:c| s|/a:|a/e c/ c :|as|e/e1 |s1es
Root node
Leaf nodes
Abe
...
Zuv
Abe
...
Irc
Ird
...
Rat
Rat
...
Zuv
Rows of
data
Rows of
data
Rows of
data
Rows of
data
Rows of
data
Rows of
data
Rows of
data
Rows of
data
Rows of
data
262 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
!n both cascs, thc numbcr ol !/ opcrations is quitc high, so you should dcsign a
nonclustcrcd indcx with carc and only whcn you arc surc that thcrc will bc signilicant
pcrlormancc gains by using it. Figurc 103 shows thc 8

trcc structurc ol a nonclustcrcd


indcx.
7ransact-SL and Indices
Now that you arc lamiliar with thc physical structurc ol indiccs, this scction dcscribcs
how you can crcatc, altcr, and drop indiccs, obtain indcx lragmcntation inlormation,
and cdit indcx inlormation, all ol which will prcparc you lor thc subscqucnt discussion
ol how you can usc indiccs to improvc pcrlormancc ol thc systcm.
Creating Indices
Thc CRAT !NX statcmcnt crcatcs an indcx lor thc particular tablc. Thc gcncral
lorm ol this statcmcnt is
CRAT |UN!QU| |CLUSTR ]NNCLUSTR| !NX indcx_namc
N tablc_namc (column1 |ASC ] SC| ,...)
| !NCLU ( column_namc | ,... | ) |
|V!TH
|F!LLFACTR-n|
||, | PA_!NX - [N ] FF]|
||, | RP_X!ST!NG - [N ] FF]|
||, | SRT_!N_TMP8 - [N ] FF]|
||qcre 1-1 :|/a:|a/e c/ c scs:|as|e/e1 |s1es
Root node
Leaf nodes
Intermediate
nodes
I1
...
I10000
I1
...
I1000
I1001
...
I2000
...
I9001
...
I10000
Row
locator
Row
locator
Row
locator
Row
locator
Row
locator
Row
locator
Row
locator
Row
locator
Row locator = RID or pointer to clustered index log
Row
locator
Cha pt er l 0: | ndi c es 263
||, | !GNR_UP_KY - [N ] FF]|
||, | ALLV_RV_LCKS - [N ] FF]|
||, |ALLV_PAG_LCKS - [N ] FF]|
||, | STAT!ST!CS_NRCMPUT - [N ] FF]|
||, |NL!N - [N ] FF]||
|N lilc_group ] "dclault"|
index_name idcntilics thc namc ol thc crcatcd indcx. An indcx can bc cstablishcd
lor onc or morc columns ol a singlc tablc (table_name). column1 is thc namc ol
thc column lor which thc indcx is crcatcd. (As you can scc lrom thc syntax ol thc
CRAT !NX statcmcnt, you can spccily an indcx lor scvcral columns ol a tablc.)
atabasc nginc supports indiccs on vicws too. Such vicws, callcd indexed .ie.s, arc
discusscd in thc ncxt chaptcr.
|c:| :c|ams c/ c |c||e, es:e(| ||cse a||| ||e |es|/|mce 1c|c |,(es, :cs |e |s1ese1. ||s mecss ||c| :c|amss
a||| l/|3||/|(///, 3|||, cs1 :9|_l/||/| 1c|c |,(es :cs |e |s1ese1, |cc.
An indcx can bc cithcr singlc or compositc. A singlc indcx has onc column, whcrcas
a compositc indcx is built on morc than onc column. ach compositc indcx has ccrtain
rcstrictions conccrning its lcngth and numbcr ol columns. Thc maximum sizc ol an
indcx is 900 bytcs, whilc thc indcx can contain up to 16 columns.
Thc UN!QU option spccilics that cach data valuc can appcar only oncc in an
indcxcd column. For a uniquc compositc indcx, thc combination ol data valucs ol all
columns in cach row must bc uniquc. !l UN!QU is not spccilicd, duplicatc valucs in
thc indcxcd column(s) arc allowcd.
Thc CLUSTR option spccilics a clustcrcd indcx. Thc NNCLUSTR
option (thc dclault) spccilics that thc indcx docs not changc thc ordcr ol thc rows in
thc tablc. atabasc nginc allows a maximum ol 249 nonclustcrcd indiccs pcr tablc.
atabasc nginc has bccn cnhanccd to support indiccs with dcsccnding ordcr on
column valucs. Thc ASC option altcr thc column namc spccilics that thc indcx is crcatcd
on thc asccnding ordcr ol thc column's valucs, whilc SC spccilics thc dcsccnding ordcr.
This givcs you morc llcxibility lor using an indcx. csccnding indiccs should bc uscd
whcn you crcatc a compositc indcx on columns that havc oppositc sorting dircctions.
Thc !NCLU option allow you to spccily thc nonkcy columns, which arc addcd
to thc lcal pagcs ol thc nonclustcrcd indcx. Column namcs cannot bc rcpcatcd in thc
!NCLU list and cannot bc uscd simultancously as both kcy and nonkcy columns.
To undcrstand thc bcnclit ol thc !NCLU option, you havc to know what a co.ering
264 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
index is. Signilicant pcrlormancc gains can bc achicvcd whcn all columns in a qucry
arc includcd in thc indcx, bccausc thc qucry optimizcr can locatc all thc column
valucs within thc indcx pagcs without having to acccss tablc data. This lcaturc is
callcd a covcring indcx or covcrcd qucry. So, il you includc additional nonkcy columns
in thc lcal pagcs ol thc nonclustcrcd indcx, morc qucrics will bc covcrcd and thcir
pcrlormancc will bc signilicantly bcttcr. (Furthcr discussion ol this topic, as wcll as an
cxamplc ol how thc qucry optimizcr handlcs a covcring indcx, can bc lound latcr in this
chaptcr in thc scction "Covcring !ndcx.")
F!LLFACTR-n dclincs thc storagc pcrccntagc lor cach indcx pagc at thc timc thc
indcx is crcatcd. You can sct thc valuc ol F!LLFACTR lrom 1 to 100. !l thc valuc ol
n is sct to 100, cach indcx pagc will bc 100 pcrccnt lillcdthat is, thc cxisting indcx
lcal pagcs as wcll as nonlcal pagcs will havc no spacc lor thc inscrtion ol ncw rows.
Thcrclorc, this valuc is rccommcndcd only lor static tablcs. (Thc dclault valuc, 0, also
indicatcs that thc lcal indcx pagcs arc lillcd and thc intcrmcdiatc nonlcal pagcs contain
onc lrcc cntry cach.)
!l you sct thc F!LLFACTR option to a valuc bctwccn 1 and 99, thc ncw indcx
structurc will bc crcatcd with lcal pagcs that arc not complctcly lull. Thc biggcr thc
valuc ol F!LLFACTR, thc smallcr thc spacc that is lclt lrcc on an indcx pagc. For
instancc, sctting F!LLFACTR to 60 mcans that 40 pcrccnt ol cach lcal indcx pagc
is lclt lrcc lor luturc inscrtion ol indcx rows. (!ndcx rows will bc inscrtcd whcn you
cxccutc cithcr thc !NSRT or thc UPAT statcmcnt.) For this rcason, thc valuc
60 could bc a rcasonablc valuc lor tablcs with rathcr lrcqucnt data modilication. For all
valucs ol thc F!LLFACTR option bctwccn 1 and 99, thc intcrmcdiatc nonlcal pagcs
contain onc lrcc cntry cach.
|e |||||/t0| |c|ae |s sc| mc|s|c|se1||c| |s, || s(e:|/|es cs|, |ca ma:| s|c/ce s(c:e |s /ese/|e1 a||| ||e
es|s||s 1c|c c| ||e ||me ||e s|c/ce (e/:es|ce |s 1e/|se1. |/ ,ca acs| |c /ees|c|||s| ||e c/||sc| |c|ae c/ ||e
|||||/t0| c(||cs, ,ca see1 |c ase ||e /||| ||||/ s|c|emes|, a||:| |s 1es:/||e1 |c|e/ |s |||s :|c(|e/.
Thc PA_!NX option is tightly conncctcd to thc F!LLFACTR option.
Thc F!LLFACTR option mainly spccilics thc pcrccntagc ol spacc that is lclt lrcc
on lcal indcx pagcs. n thc othcr hand, thc PA_!NX option spccilics that thc
F!LLFACTR sctting should bc applicd to thc indcx pagcs as wcll as to thc data pagcs
in thc indcx.
Thc RP_X!ST!NG option allows you to cnhancc pcrlormancc whcn rccrcating
a clustcrcd indcx on a tablc that also has a nonclustcrcd indcx. Scc thc scction 'Rcbuilding
an !ndcx' latcr in thc chaptcr lor morc dctails.
Thc SRT_!N_TMP8 option is uscd to placc into thc tempdb systcm databasc
thc data lrom intcrmcdiatc sort opcrations uscd whilc crcating thc indcx. This can
Cha pt er l 0: | ndi c es 265
rcsult in a pcrlormancc bcnclits il thc tempdb databasc is placcd on anothcr disk drivc
lrom thc data itscll. (RP_X!ST!NG is discusscd in thc scction "Rcbuilding an
!ndcx" latcr in thc chaptcr.)
Thc !GNR_UP_KY option causcs thc systcm to ignorc thc attcmpt to inscrt
duplicatc valucs in thc indcxcd column(s). This option should bc uscd only to avoid
thc tcrmination ol a long transaction in cascs whcn thc !NSRT statcmcnt inscrts
duplicatc data in thc indcxcd column(s). !l this option is activatcd and an !NSRT
statcmcnt attcmpts to inscrt rows that would violatc thc uniqucncss ol thc indcx, thc
databasc systcm rcturns a warning rathcr than causing thc cntirc statcmcnt to lail.
atabasc nginc docs not inscrt thc rows that would add duplicatc kcy valucs, it mcrcly
ignorcs thosc rows and adds thc rcst. (!l this options is not sct, thc statcmcnt as a wholc
will bc abortcd.)
Thc ALLV_RV_LCKS option spccilics that thc systcm uscs row locks
whcn this option is activatcd (sct to N). Similarly, thc ALLV_PAG_LCKS
option spccilics that thc systcm uscs pagc locks whcn this option is sct to N. (For thc
dcscription ol pagc and row locks, scc Chaptcr 13.)
Thc STAT!ST!CS_NRCMPUT option spccilics that statistics ol thc
spccilicd indcx should not bc automatically rccomputcd. Thc N option crcatcs cithcr
thc spccilicd indcx on thc dclault lilc group ("dclault") or on thc spccilicd lilc group
(file_group).
!l you activatc thc NL!N option, you can crcatc, rcbuild, or drop an indcx onlinc.
This option allows concurrcnt modilications to thc undcrlying tablc or clustcrcd indcx
data and any associatcd indiccs during indcx cxccution. For cxamplc, whilc a clustcrcd
indcx is bcing rcbuilt, you can continuc to makc updatcs to thc undcrlying data and
pcrlorm qucrics against thc data. (This mcans that cxclusivc locks on thc undcrlying
data arc not hcld during indcx rcbuilding.)
3e/c/e ,ca s|c/| |c ese:a|e ae/|es |s |||s :|c(|e/, /e-:/ec|e ||e es||/e 1c|c|cse.

xamplc 10.1 shows thc crcation ol a nonclustcrcd indcx.
XAMPL 10.1
Crcatc an indcx lor thc emp_no column ol thc employee tablc:
US samplc,
CRAT !NX i_cmpno N cmploycc (cmp_no),
xamplc 10.2 shows thc crcation ol a uniquc compositc indcx.
266 Mi c r os of t S QL S er v er 2 00 8: A 8egi nner ' s Gui de
XAMPL 10.2
Crcatc a compositc indcx lor thc columns emp_no and project_no on thc works_on
tablc. Thc compound valucs in both columns must bc uniquc. ighty pcrccnt ol cach
indcx lcal pagc should bc lillcd.
US samplc,
CRAT UN!QU !NX i_cmpno_prno
N works_on (cmp_no, projcct_no)
V!TH F!LLFACTR- 80,
Thc crcation ol a uniquc indcx lor a column is not possiblc il thc column alrcady
contains duplicatc valucs. Thc crcation ol such an indcx is possiblc il cach cxisting
data valuc (including thc NULL valuc) occurs only oncc. Also, any attcmpt to inscrt
or modily an cxisting data valuc into a column with an cxisting uniquc indcx will bc
rcjcctcd by thc systcm.
Dbtaining Index Fragmentation Information
uring thc lilc cyclc ol an indcx, it can bccomc fragmented, mcaning thc storagc ol
data in its pagcs is donc incllicicntly. Thcrc arc two lorms ol indcx lragmcntation:
intcrnal and cxtcrnal. !ntcrnal lragmcntation spccilics thc amount ol data, which is
storcd within cach pagc. xtcrnal lragmcntation occurs whcn thc logical ordcr ol thc
pagcs is wrong.
To gct inlormation conccrning intcrnal indcx lragmcntation, you usc cithcr thc
dynamic managcmcnt vicw (M\) callcd sys.dm_db_index_physical_stats or thc
8CC SHVCNT!G command. This scction discusscs only thc M\, bccausc
8CC SHVCNT!G is a dcprccatcd lcaturc.
sys.dm_db_index_physical_stats rcturns sizc and lragmcntation inlormation lor
thc data and indiccs ol thc spccilicd tablc. For cach indcx, onc row is rcturncd lor cach
lcvcl 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

S-ar putea să vă placă și