You are on page 1of 135

Visit: www.gcreddy.

com for QTP Information


SQL Server Guide
For Software Testers
Visit: www.gcreddy.net for Testing Information
1
Visit: www.gcreddy.com for QTP Information
Index
Introduction 2
Structured Query Language (SQL) 10
Dataases 11
Ta!es 22
"onstraints #2
$oins %2
&ui!t'in Functions %(
Visit: www.gcreddy.net for Testing Information
2
Visit: www.gcreddy.com for QTP Information
Su'Queries ))
*iews +1
Indexes +%
,or-a!i.ation +(
T'SQL (0
Stored /rocedures (%
Triggers (+
0ser Defined Functions (0DF) 11
Loc2s 1)
Transactions 13
SQL Server Security 3#
&ac2'u/ and recoveries 3(
4dvanced features (SQL 200)) 101
"ase Study 12+
Visit: www.gcreddy.net for Testing Information
3
Visit: www.gcreddy.com for QTP Information
I,T56D0"TI6,
SQL Server is a Client/Server Relational Dataase !anagement System
"RD#!S$ t%at &ses Transact'SQL to send re(&est etween a client and SQL Server.
"!ient7Server 4rc8itecture9
SQL Server is designed to e a client/server system. Client/server systems
are constr&cted so t%at t%e dataase can reside on a central com)&ter* +now as a
Server* and e s%ared among several &sers. ,%en &sers want to access t%e data in
SQL Server* t%ey r&n an a))lication on t%eir local com)&ter* +nown as a Client t%at
connects over a networ+ to t%e server r&nning SQL Server.
SQL Server can wor+ wit% t%o&sands of client a))lication sim&ltaneo&sly. T%e
server %as feat&res to )revent t%e logical )rolems t%at occ&r if a &ser tries to read
or modify data c&rrently &sed y ot%ers.
,%ile SQL Server is designed to wor+ as a sever in a Client/Server networ+* it
is also ca)ale of wor+ing as a stand'alone dataase directly on t%e client. T%e
scalaility and easy'to'&se feat&res of SQL Server allow it to wor+ efficiently on a
client wit%o&t cons&ming too many reso&rces.
To egin wit%* a rief overview of t%e relational dataase model is )rovided as
t%e SQL Server dataase is ased on t%is model.
6verview of 5D&:S9
Data9' Information t%at is een stored and &sed in t%e com)&ter system is called as
data.
Dataase9' Collection of meaningf&l Information stored in an organi-ed manner.
Visit: www.gcreddy.net for Testing Information
4
Visit: www.gcreddy.com for QTP Information
D&:S9' It is a collection of interrelated data and a set of )rograms to access and
modify t%e data.
5D&:S9' It is also D#!S &t t%e relation will e stored into t%e dataase.
Differences &etween D&:S 4nd 5D&:S9'
D&:S 5D&:S
In D#!S data is stored in t%e form of a
file and is s%own to t%e &ser in t%e form
of a two dimensional tale.
In t%e case of RD#!S data is strictly to
e stored in t%e form of tale and also
s%own in t%e form of tale.
In D#!S t%e relation s%i) estalis%ed
among t%e tales will not e stored into
t%e dataase.
In RD#!S t%e relations%i) estalis%ed
will e stored into t%e dataase as one of
t%e dataase o.ects.
5e!ations8i/s a-ong Data9
/ relations%i) is defined as 0an association among entities1. T%e t%ree
different ty)es of relations%i)s recogni-ed among vario&s data stored in t%e dataase
are:
6ne'to'one
In a one'to'one relations%i)* a row in tale / can %ave no more t%an one matc%ing
row in tale #* and vice versa.
6ne'to'-any
/ one'to'many relations%i) is t%e most common ty)e of relations%i). In t%is ty)e of
relations%i)* a row in tale / can %ave many matc%ing rows in tale #* &t a row in
tale # can %ave only one matc%ing row in tale /.
:any'to'-any
In a many'to'many relations%i)* a row in tale / can %ave many matc%ing rows in
tale #* and vice versa. 2o& create s&c% a relations%i) y defining a t%ird tale*
called a .&nction tale.
Data :ode!9'
It is not%ing &t t%e str&ct&re in w%ic% t%e data is stored in t%e dataase.
T%ere are two im)ortant data models e3isting. T%ey are:
4.5.ect'ased data model 6. Record'ased data model.
6;ect < &ased Data :ode!9' It is a collection of conce)t&al tool for descriing t%e
data* data relations%i)s and data constraints.
5ecord < &ased Data :ode!9' It descries t%e data str&ct&res and access
tec%ni(&es of D#!S. 5.ect 7ased data model is t%e conce)t and Record'ase data
model is t%e act&al re)resentation of t%e data in t%e dataase.
Visit: www.gcreddy.net for Testing Information
5
Visit: www.gcreddy.com for QTP Information
5f all t%e different 5.ect'ased data models availale t%e most )o)&lar model is 8/R
Diagram and from t%e vario&s record'ased data models t%e )o)&lar and
effective model is t%e Relational model.
:S SQL S=5*=5 2000
SQL S8RV8R is a !icrosoft ac+'office )rod&ct t%at is de)loyed on windows
environment. SQL S8RV8R is a SQL ased client/server* Relational Dataase
!anagement System. SQL stands for Str&ct&red Q&ery Lang&age* w%ic% is &sed in
writing (&eries to retrieve data from dataases. SQL Server stores data at a central
location +nown as Server, and delivers it on demand to ot%er locations +nown as
Clients. T%e server is res)onsile for manage t%e dataase and to allocate availale
server reso&rces s&c% as dis+ o)erations* and memory for m&lti)le re(&ests. T%e
client is res)onsile for )resenting data and &siness logic to t%e end'&ser. Client
)rogramming interfaces )rovide t%e means for a))lications to r&n on se)arate client
com)&ters and comm&nicate to t%e server over networ+.
Some of t%e advantages of SQL client are:
S&))orts m&lti)le %ardware )latforms
S&))orts m&lti)le software )latforms
Some advantages of SQL server are:
Reliale
9a&lt tolerant
Centrali-ed control
Conc&rrent
So)%isticated loc+ing
SQL S8RV8R is SCALABLE, RELIABLE, INTEROPERABLE, HIGH PERFORMANCE* and
CLIENT / SERVER RDBMS.
Sca!ai!ity9 T%e conce)t of scalaility is s&))orting )arallel )rocessing wit% more
t%an one server. T%e necessity for more t%an one server is t%e sit&ation w%ere in
server is %eld &) wit% one client re(&est and all t%e ot%er clients are in waiting for
t%at server relived from t%at client )rocess* t%en t%e client internally re(&ests t%e
ot%er server to ta+e over t%e activities on t%e networ+. T%e ot%er sit&ation w%ere in
we need m&lti)le servers is 7 if in case t%e dataase is e3tended across t%e m&lti)le
servers and a client re(&ests for a dataase o.ect w%ic% mig%t e on some ot%er
servers* t%en t%e server to w%ic% t%e re(&est %as een )assed on searc%es for t%at
dataase o.ect and retrieves t%e data from ot%er servers also.
5e!iai!ity9 It is recovering t%e data even in t%e case of system cras% wit% a
minim&m loss of data. T%at is )ossile y t%e means t%at t%e server will re)licate t%e
same data into different memory locations w%ic% is called as R8PLIC/TI5:. 8ven in
t%e case of loss of data in t%e )rimary location also data can get from t%e secondary
locations
Intero/erai!ity9 It is t%e aility of SQL S8RV8R to comm&nicate wit% ot%er
RD#!S li+e D#6* I!S and 5R/CL8. T%is is if t%e dataase is already availale in
ot%er RD#!S t%at can e getting into SQL S8RV8R wit% t%e %el) of a conce)t called
I!P5RT. Similarly if t%e dataase is availale is SQL S8RV8R can e ta+en into ot%er
RD#!S wit% t%e %el) of t%e conce)t called 8;P5RT.
Visit: www.gcreddy.net for Testing Information
6
Visit: www.gcreddy.com for QTP Information
<ig% Performance: 8ven in t%e case of &l+ dataases t%e SQL S8RV8R )erforms
inserts* &)dates from t%e dataase wit% res)onse time to t%e order of
milliseconds. / dataase is a collection of tales and o.ects li+e views* inde3es*
stored )roced&res and triggers.
=DITI6,S 6F SQL S=5*=5
!icrosoft SQL Server 6=== comes wit% different editions. T%e following are t%e
editions t%at are availale.
SQL Server 2000 =nter/rise =dition
>sed as a )rod&ction dataase server. S&))orts all feat&res availale in SQL Server
6===* and scales to t%e )erformance levels re(&ired to s&))ort t%e largest ,e sites
and enter)rise online transaction )rocessing "5LTP$ and data ware%o&sing systems.
SQL Server 2000 Standard =dition
>sed as a dataase server for a small wor+gro&) or de)artment.
SQL Server 2000 >ersona! =dition
>sed y moile &sers w%o s)end some of t%eir time disconnected from t%e networ+
&t r&n a))lications t%at re(&ire SQL Server data storage. /lso &sed w%en r&nning a
stand'alone a))lication t%at re(&ires local SQL Server data storage on a client
com)&ter.
SQL Server 2000 Deve!o/er =dition
>sed y )rogrammers develo)ing a))lications t%at &se SQL Server 6=== as t%eir
data store. /lt%o&g% t%e Develo)er 8dition s&))orts all t%e feat&res of t%e 8nter)rise
8dition t%at allow develo)ers to write and test a))lications t%at can &se t%e feat&res*
t%e Develo)er 8dition is licensed for &se only as a develo)ment and test system* not
a )rod&ction server.
SQL Server 2000 ?indows "= =dition
!icrosoft? SQL Server 6===@ ,indows? C8 8dition "SQL Server C8$ is &sed as t%e
data store on ,indows C8 devices. Ca)ale of re)licating data wit% any edition of
SQL Server 6=== to +ee) ,indows C8 data sync%roni-ed wit% t%e )rimary dataase.
5&t of all t%e editions* 8nter)rise 8dition is t%e most feat&red one.
8nter)rise 8dition allows A6 )rocessors to e added to t%e server mac%ine in
s&))ort to Syetri! M"lti Pr#!essin$.
Develo)er 8dition allows B )rocessors to e added to t%e server.
In general Develo)er 8dition is &sed at t%e time of develo)ing t%e a))lication
and 8nter)rise 8dition is &sed as t%e Prod&ction Server.
Visit: www.gcreddy.net for Testing Information
7
Visit: www.gcreddy.com for QTP Information
4d-inistrative Too!s
!icrosoft? SQL Server@ 6=== incl&des many gra)%ical and command )rom)t
&tilities t%at allow &sers* )rogrammers* and administrators to:
/dminister and config&re SQL Server.
Determine t%e catalog information in a co)y of SQL Server.
Design and test (&eries for retrieving data.
Co)y* im)ort* e3)ort* and transform data.
Provide diagnostic information.
Start and sto) SQL Server.
In addition to t%ese &tilities* SQL Server contains several wi-ards to wal+
administrators and )rogrammers t%ro&g% t%e ste)s needed to )erform more com)le3
administrative tas+s.
T%e tools t%at are s&))orted y SQL Server are
#oo+s 5nline
Client :etwor+ >tility
8nter)rise !anager
Q&ery /naly-er
Im)ort and 83)ort Data
SQL Profiler
Service Manager
Books online:
This tool can be used as help for SQL Server database. Any information
regarding SQL Server can be found with this tool. It consists of syntaxes
and examples for all topics of SQL Server database.
Client Network Utility:
T%is tool is &sed to config&re a client mac%ine wit% a server.
T%e Client :etwor+ &tility is &sed to manage t%e client :et'Liraries and
define server alias names. It can also e &sed to set t%e defa&lt o)tions &sed y D#'
Lirary a))lications.
Visit: www.gcreddy.net for Testing Information
8
Visit: www.gcreddy.com for QTP Information
!ost &sers will never need to &se t%e Client :etwor+ &tility. To connect to
!icrosoft? SQL Server@ 6===* &sers can s)ecify only t%e networ+ name of t%e
server on w%ic% SQL Server is r&nning* and o)tionally t%e name of t%e instance of
SQL Server.
In some cases* an instance of SQL Server may e config&red to listen on
alternate networ+ addresses. If t%is is done* client a))lications connecting to t%at
instance m&st e3)licitly s)ecify t%e alternate address. ,%ile a))lications co&ld
s)ecify t%e alternate addresses on eac% connection re(&est* it is easier to &se t%e
Client :etwor+ &tility to set &) an alias s)ecifying t%e alternate addresses.
/))lications can t%en s)ecify t%e alias name in )lace of t%e server networ+ name in
t%eir connection re(&ests.
=nter/riser :anager9
S%L Server Enter&rise M'n'$er is t%e )rimary administrative tool for !icrosoft? SQL
Server@ 6=== and )rovides a !icrosoft !anagement Console "!!C$7com)liant &ser
interface t%at allows &sers to:
Define gro&)s of servers r&nning SQL Server.
Register individ&al servers in a gro&).
Config&re all SQL Server o)tions for eac% registered server.
Create and administer all SQL Server dataases* o.ects* logins* &sers* and
)ermissions in eac% registered server.
Define and e3ec&te all SQL Server administrative tas+s on eac% registered
server.
Design and test SQL statements* atc%es* and scri)ts interactively y
invo+ing SQL Q&ery /naly-er.
Invo+e t%e vario&s wi-ards defined for SQL Server.
Query 4na!y.er9
S%L %"ery An'ly(er is a gra)%ical &ser interface for designing and testing Transact'
SQL statements* atc%es* and scri)ts interactively. SQL Q&ery /naly-er can e called
from SQL Server 8nter)rise !anager.
SQL Q&ery /naly-er offers:
/ 9ree'form te3t editor for +eying in Transact'SQL statements.
Color'coding of Transact'SQL synta3 to im)rove t%e readaility of com)le3
statements.
5.ect rowser and o.ect searc% tools for easily finding t%e o.ects in a
dataase and t%e str&ct&re of t%e o.ects.
Tem)lates t%at can e &sed to s)eed develo)ment of t%e Transact'SQL
statements for creating SQL Server o.ects. Tem)lates are files t%at incl&de
t%e asic str&ct&re of t%e Transact'SQL statements needed to create o.ects
in a dataase.
/n interactive de&gger for analy-ing stored )roced&res.
Res&lts )resented in eit%er a grid or a free'form te3t window.
Visit: www.gcreddy.net for Testing Information
9
Visit: www.gcreddy.com for QTP Information
Cra)%ical diagram of t%e s%ow )lan information s%owing t%e logical ste)s &ilt
into t%e e3ec&tion )lan of a Transact'SQL statement.
T%is allows )rogrammers to determine w%at s)ecific )art of a )oorly
)erforming (&ery is &sing a lot of reso&rces. Programmers can t%en e3)lore
c%anging t%e (&ery in ways t%at minimi-e t%e reso&rce &sage w%ile still
ret&rning t%e correct data.
Inde3 T&ning ,i-ard to analy-e a Transact'SQL statement and t%e tales it
references* to see if adding additional inde3es will im)rove t%e )erformance of
t%e (&ery.
I-/ort and =x/ort Data
T%e I&#rt 'n) E*&#rt D't' item in t%e !icrosoft? SQL Server@ )rogram
gro&) starts t%e Data Transformation Services "DTS$ Im)ort/83)ort ,i-ard. T%e
wi-ard wal+s &sers t%ro&g% t%e DTS f&nctions of im)orting* e3)orting* validating* and
transforming data and o.ects etween %eterogeneo&s 5L8 D# and 5D#C data
so&rces.
SQL >rofi!er
S%L Pr#+iler is a tool t%at ca)t&res !icrosoft? SQL Server@ 6=== events from a
server. T%e events are saved in a trace file t%at can later e analy-ed or &sed to
re)lay a s)ecific series of ste)s w%en trying to diagnose a )rolem. SQL Profiler is
&sed for activities s&c% as:
Ste))ing t%ro&g% )rolem (&eries to find t%e ca&se of t%e )rolem.
9inding and diagnosing slow'r&nning (&eries.
Ca)t&ring t%e series of SQL statements t%at lead to a )rolem. T%e saved
trace can t%en e &sed to re)licate t%e )rolem on a test server w%ere t%e
)rolem can e diagnosed.
!onitoring t%e )erformance of SQL Server to t&ne wor+loads.
SQL Profiler also s&))orts a&diting t%e actions )erformed on instances of SQL Server.
/&dits record sec&rity'related actions for later review y a sec&rity administrator.
SQL Server 6=== a&diting meets C6 sec&rity certification re(&irements.
SQL Server Service :anager9
SQL Server Service !anager is &sed to start* sto)* and )a&se t%e !icrosoft? SQL
Server@ 6=== com)onents on t%e server. T%ese com)onents r&n as services on
!icrosoft ,indows :T? or !icrosoft ,indows? 6=== and as se)arate e3ec&tale
)rograms on !icrosoft ,indows DE and !icrosoft ,indows DF:
SQL Server Service !anager is a tas+ar a))lication and follows t%e standard
e%avior of tas+ar a))lications. ,%en minimi-ed* t%e SQL Server Service
:anager icon " $ a))ears in t%e area of t%e tas+ar cloc+ on t%e rig%t of t%e
Visit: www.gcreddy.net for Testing Information
10
Visit: www.gcreddy.com for QTP Information
tas+ar. To get a men& t%at incl&des all t%e tas+s SQL Server Service !anager
s&))orts* rig%t'clic+ t%e tas+ar item.
To ma3imi-e SQL Server Service !anager* do&le'clic+ t%e icon. T%e SQL Server
Service !anager ,indow a))ears as follows.
,%en SQL Server Service !anager is ma3imi-ed* clic+ing t%e close &tton of t%e SQL
Server Service !anager window does not terminate t%e a))licationG it only minimi-es
SQL Server Service !anager to t%e tas+ar. To terminate SQL Server Service
!anager* rig%t'clic+ t%e SQL Server Service :anager icon on t%e tas+ar* and t%en
select t%e Fi!e/=xit men& item.
ST50"T05=D Q0=5@ L4,G04G=
SQL is a standard t%at every dataase s%o&ld follow. T%at means all t%e SQL
commands s%o&ld wor+ in all dataases. #ased on t%e ty)e of o)erations we are
)erforming on t%e dataase* SQL is divided into t%ree ty)es. T%ey are:
Data Definition Lang&age "DDL$
Data !ani)&lation Lang&age "D!L$
Transaction Control Lang&age "TCL$
Data Definition Language9
It is &sed to create an o.ect "e.g. tale$* alter t%e str&ct&re of an o.ect and
also to delete t%e o.ect created. /ll t%ese commands will effects t%e str&ct&re of t%e
dataase o.ect. T%e commands contained y t%is lang&age are:
CR8/T8 ' &sed to create an o.ect
/LT8R ' &sed to modify an e3isting o.ect
DR5P ' &sed to delete t%e o.ect
TR>:C/T8 ' &sed to delete only t%e data of an o.ect
Data :ani/u!ation Language9
T%e D!L commands are most fre(&ently &sed SQL commands. T%ey are &sed
to (&ery and mani)&late e3isting o.ects li+e tales. T%ey s%o&ld affect only t%e data
of an e3isting str&ct&re. T%e commands e3isting in t%is lang&age are:
S8L8CT ' &sed to (&ery t%e o.ect data
I:S8RT ' &sed to enter t%e data into t%e o.ect
>PD/T8 ' &sed to modify e3isting o.ects data
D8L8T8 ' &sed to delete t%e data of an o.ect.
Transaction "ontro! Language9
/ transaction is a logical &nit of wor+. /ll c%anges made to t%e dataase can
e referred to as a transaction. Transaction c%anges can e controlled wit% t%e &se of
t%is lang&age commands. T%ey are:
C5!!IT ' &sed to ma+e t%e c%anges )ermanent
R5LL#/CH ' &sed to &ndo t%e c%anges
Visit: www.gcreddy.net for Testing Information
11
Visit: www.gcreddy.com for QTP Information
D4T4&4S=S
/ dataase in !icrosoft? SQL Server@ 6=== consists of a collection of tales
t%at contain data and ot%er o.ects* s&c% as views* inde3es* stored )roced&res* and
triggers* defined to s&))ort activities )erformed wit% t%e data. T%e data stored in a
dataase is &s&ally related to a )artic&lar s&.ect or )rocess* s&c% as inventory
information for a man&fact&ring ware%o&se.
SQL Server can s&))ort many dataases. 8ac% dataase can store eit%er interrelated
or &nrelated data from ot%er dataases. 9or e3am)le* a server can %ave one
Visit: www.gcreddy.net for Testing Information
12
Visit: www.gcreddy.com for QTP Information
dataase t%at stores )ersonnel data and anot%er t%at stores )rod&ct'related data.
/lternatively* one dataase can store c&rrent c&stomer order data* and anot%er
related dataase can store %istorical c&stomer orders &sed for yearly re)orting.
#efore yo& create a dataase* it is im)ortant to &nderstand t%e )arts of a dataase
and %ow to design t%ese )arts to ens&re t%at t%e dataase )erforms well after it is
im)lemented.
Dataase 4rc8itecture
!icrosoft? SQL Server@ 6=== data is stored in dataases. T%e data in a dataase is
organi-ed into t%e logical com)onents visile to &sers. / dataase is also )%ysically
im)lemented as two or more files on dis+.
,%en &sing a dataase* yo& wor+ )rimarily wit% t%e logical com)onents s&c% as
tales* views* )roced&res* and &sers. T%e )%ysical im)lementation of files is largely
trans)arent. Ty)ically* only t%e dataase administrator needs to wor+ wit% t%e
)%ysical im)lementation.
8ac% instance of SQL Server %as fo&r system dataases "-aster* -ode!* te-/d*
and -sd$ and one or more &ser dataases. Some organi-ations %ave only one &ser
dataase* containing all t%e data for t%eir organi-ation. Some organi-ations %ave
different dataases for eac% gro&) in t%eir organi-ation* and sometimes a dataase
&sed y a single a))lication. 9or e3am)le* an organi-ation co&ld %ave one dataase
for sales* one for )ayroll* one for a doc&ment management a))lication* and so on.
Sometimes an a))lication &ses only one dataaseG ot%er a))lications may access
several dataases.
Visit: www.gcreddy.net for Testing Information
13
Visit: www.gcreddy.com for QTP Information
It is not necessary to r&n m&lti)le co)ies of t%e SQL Server dataase engine to allow
m&lti)le &sers to access t%e dataases on a server. /n instance of t%e SQL Server
Standard or 8nter)rise 8dition is ca)ale of %andling t%o&sands of &sers wor+ing in
m&lti)le dataases at t%e same time. 8ac% instance of SQL Server ma+es all
dataases in t%e instance availale to all &sers t%at connect to t%e instance* s&.ect
to t%e defined sec&rity )ermissions.
Ty/es of Dataases9
SQL Server )rovides two ty)es of Dataases.
System Dataases
>ser Defined Dataases
Syste- Dataases9
/long wit% t%e installation of SQL Server FOUR dataases will e created
a&tomatically called as system dataases. T%ey are:
-aster
T%e -aster dataase records all of t%e system level information for a SQL
Server system. It records all login acco&nts and all system config&ration
settings. -aster is t%e dataase t%at records t%e e3istence of all ot%er
dataases* incl&ding t%e location of t%e dataase files. -aster records t%e
initiali-ation information for SQL ServerG always %ave a recent ac+&) of
-aster availale.
-ode!
T%e -ode! dataase is &sed as t%e tem)late for all dataases created on a
system. ,%en a CR8/T8 D/T/#/S8 statement is iss&ed* t%e first )art of t%e
Visit: www.gcreddy.net for Testing Information
14
Visit: www.gcreddy.com for QTP Information
dataase is created y co)ying in t%e contents of t%e -ode! dataase* t%en
t%e remainder of t%e new dataase is filled wit% em)ty )ages. #eca&se
te-/d is created every time SQL Server is started* t%e -ode! dataase
m&st always e3ist on a SQL Server system.
-sd
T%e -sd dataase is &sed y SQL Server /gent for sc%ed&ling alerts and
.os* and recording o)erators.
te-/d
te-/d %olds all tem)orary tales and tem)orary stored )roced&res. It also
fills any ot%er tem)orary storage needs s&c% as wor+ tales generated y SQL
Server. te-/d is a gloal reso&rceG t%e tem)orary tales and stored
)roced&res for all &sers connected to t%e system are stored t%ere. te-/d is
re'created every time SQL Server is started so t%e system starts wit% a clean
co)y of t%e dataase. #eca&se tem)orary tales and stored )roced&res are
dro))ed a&tomatically on disconnect* and no connections are active w%en t%e
system is s%&t down* t%ere is never anyt%ing in te-/d to e saved from
one session of SQL Server to anot%er.
0ser Defined Dataases9
T%e dataases t%at are created y t%e &sers are called as &ser defined
dataases. ,%ile creating a dataase t%e &ser %as to s)ecify a name to t%e dataase
and t%e details of data files* w%ic% are &sed to s)ecify t%e location* w%ere t%e
dataase data is to e stored.
Fi!es and Fi!egrou/s
!icrosoft? SQL Server@ 6=== ma)s a dataase &sing a set of o)erating'system
files. /ll data and o.ects in t%e dataase* s&c% as tales* stored )roced&res*
triggers* and views* are stored wit%in t%ese o)erating'system files:
Primary Data 9ile ".mdf$
T%is file contains t%e start&) information for t%e dataase and is &sed to store
data. 8very dataase %as one )rimary data file.
Secondary Data 9ile ".ndf$
T%ese files %old all of t%e data t%at does not fit in t%e )rimary data file. If t%e
)rimary file can %old all of t%e data in t%e dataase* dataases do not need to
%ave secondary data files. Some dataases may e large eno&g% to need
m&lti)le secondary data files or to &se secondary files on se)arate dis+ drives
to s)read data across m&lti)le dis+s.
Transaction Log 9ile ".ldf$
T%ese files %old t%e log information &sed to recover t%e dataase. T%ere m&st
e at least one log file for eac% dataase.
Visit: www.gcreddy.net for Testing Information
15
Visit: www.gcreddy.com for QTP Information
9ilegro&)s allow files to e gro&)ed toget%er for administrative and data
allocation/)lacement )&r)oses. 9or e3am)le* t%ree files "Data4.ndf* Data6.ndf* and
DataA.ndf$ can e created on t%ree dis+ drives* res)ectively* and assigned to t%e
filegro&) fgrou/1. / tale can t%en e created s)ecifically on t%e filegro&) fgrou/1.
Q&eries for data from t%e tale will e s)read across t%e t%ree dis+s* t%erey
im)roving )erformance. 9iles and filegro&)s* %owever* allow yo& to easily add new
files on new dis+s. /dditionally* if yo&r dataase e3ceeds t%e ma3im&m si-e for a
single !icrosoft ,indows :T? file* yo& can &se secondary data files to allow yo&r
dataase to contin&e to grow.
"reating a Dataase9
To create a dataase determine t%e name of t%e dataase* its owner "t%e &ser w%o
creates t%e dataase$* its si-e* and t%e files and filegro&)s &sed to store it.
#efore creating a dataase* consider t%at:
Permission to create a dataase defa&lts to memers of t%e sysad-in and
dcreator fi3ed server roles* alt%o&g% )ermissions can e granted to ot%er
&sers.
T%e &ser w%o creates t%e dataase ecomes t%e owner of t%e dataase.
/ ma3im&m of A6*IJI dataases can e created on a server.
T%e name of t%e dataase m&st follow t%e r&les for identifiers.
/ dataase can e created eit%er y &sing 8nter)rise !anager or y &sing Q&ery
/naly-er.
0sing =nter/rise :anger to "reate Dataase9
To create a dataase &sing 8nter)rise !anager &se t%e following ste)s:
4. 5)en t%e 8nter)rise from ST/RT &tton as follows:
Start 'K Programs 'K !icrosoft SQL Server 'K 8nter)rise !anager
6. 83)and a server gro&)* and t%en e3)and a server
A. Rig%t'clic+ Dataases* and t%en clic+ ,ew Dataase.
B. 8nter a name for t%e new dataase.
Visit: www.gcreddy.net for Testing Information
16
Visit: www.gcreddy.com for QTP Information
T%e )rimary dataase and transaction log files are created &sing t%e dataase
name yo& s)ecified as t%e )refi3* for e3am)le newdLData.mdf and
newwdLLog.ldf. T%e initial si-es of t%e dataase and transaction log files are
t%e same as t%e defa&lt si-es s)ecified for t%e -ode! dataase. T%e )rimary
file contains t%e system tales for t%e dataase.
E. To c%ange t%e defa&lt val&es for t%e new )rimary dataase file* clic+ t%e Data
Fi!es ta. To c%ange t%e defa&lts for t%e new transaction log file* clic+ t%e
Transaction Log ta.
J. To c%ange t%e defa&lt val&es )rovided in t%e Fi!e na-e* Location* Initia!
si.e (:&)* and Fi!e grou/ "not a))licale for t%e transaction log$ col&mns*
clic+ t%e a))ro)riate cell to c%ange and enter t%e new val&e.
I. To s)ecify %ow t%e file s%o&ld grow* select from t%ese o)tions:
To allow t%e c&rrently selected file to grow as more data s)ace is
needed* select 4uto-atica!!y grow fi!e.
To s)ecify t%at t%e file s%o&ld grow y fi3ed increments* select In
-egaytes and s)ecify a val&e.
To s)ecify t%at t%e file s%o&ld grow y a )ercentage of t%e c&rrent file
si-e* select &y /ercent and s)ecify a val&e.
F. To s)ecify t%e file si-e limit* select from t%ese o)tions:
To allow t%e file to grow as m&c% as necessary* select 0nrestricted
fi!egrowt8.
To s)ecify t%e ma3im&m si-e t%e file s%o&ld e allowed to grow to*
select 5estrict fi!egrowt8 (:&) and s)ecify a val&e.
,ote9 T%e ma3im&m dataase si-e is determined y t%e amo&nt of dis+ s)ace
availale and t%e licensing limits determined y t%e version of !icrosoft? SQL
Server@ yo& are &sing.
Visit: www.gcreddy.net for Testing Information
17
Visit: www.gcreddy.com for QTP Information
0sing Query 4na!y.er9
To &se t%e Q&ery /naly-er tool* &se t%e following ste)s.
4. 5)en t%e tool from t%e start men& as follows:
Start 'K Programs 'K !icrosoft SQL Server 'K Q&ery /naly-er
6. S)ecify t%e details of server from t%e dro) down &tton.
A. Select t%e a&t%entication ty)e from one of t%e o)tion &ttons.
B. clic+ ,O-..
E. To e3ec&te any command* ty)e t%e command in t%e em)ty area and )ress t%e
,E*e!"te %"ery /F01. icon on t%e tool ar.
,e can also &se t%e 8nter)rise !anger tool to o)en Q&ery /naly-er. To do
t%is* in t%e 8nter)rise !anager* C%oose Too!s 'A SQL Query 4na!y.er men&
item and t%e aove ste)s as it is.
"reating a Dataase 0sing Query 4na!y.er9
5nce t%e Q&ery /naly-er is o)ened* in t%e command window we can write
any command t%at %as to e e3ec&ted.
Syntax9
:ote: 2L#$i!'l+ilen'e3 is &sed to identity t%e file for f&rt%er modifications and 2#s4
+ilen'e3 refers t%e original location w%ere t%e file is stored in t%e %ard dis+.
Visit: www.gcreddy.net for Testing Information
18
CREATE DATABASE databasename
[ON]
(NAME=<logical fle name>,
FILENAME=<os-flename>,
SIZE=<in mbs>,MAXSIZE=<in mbs>,FILEGROWTH=<in mbs>)]
[LOG ON
(NAME=<logical fle name>,
FILENAME=<os-flename>,
SIZE=<in mbs>,MAXSIZE=<in mbs>,FILEGROWTH=<in mbs>)]
Visit: www.gcreddy.com for QTP Information
=xa-/!e9
:6DIF@I,G 4 D4T4&4S=9
T%e c%anges t%at can e made to e3isting dataase are
T%e data and log files can e added or removed.
T%e dataase can e made to e3)and or s%rin+
9ile gro&)s can e added and removed from t%e dataase.
T%e config&ration settings for t%e dataase can e c%anged
T%e dataase can e e3)anded y allocating additional s)ace to t%e e3isting
dataase file or y allocating s)ace to a new file. T%e si-e of t%e dataase m&st e
increased y at least 4m.
/ ma3im&m si-e s%o&ld e s)ecified &sing t%e !/;SIM8 )arameter of t%e /LT8R
D/T/#/S8 statement. T%is )revents t%e file from growing &ntil t%e dis+ s)ace is
e3%a&sted.
Syntax9
Example:
Visit: www.gcreddy.net for Testing Information
19
CREATE DATABASE emp
ON
(NAME=emp-dat,
FILENAME=d:\backup\data\emp_dat.mdf,
SIZE=15,MAXSIZE=50,FILEGROWTH=5)
LOG ON
(NAME=emp-Log,
FILENAME=d:\backup\log\emp_log.ldf,
SIZE=10,MAXSIZE=25,FILEGROWTH=5)
ALTER DATABASE <database Name>
ADD FILE <fle specifcations>
|ADD LOG FILE <fle specifcations>
|REMOVE FILE <fle name>
|ADD FILEGROUP <fle group name>
|REMOVE FILEGROUP <fle group name>
|MODIFY FILE <fle specifcations>
|MODIFY FILEGROUP <fle group name>
ALTER DATABASE emp
ADD FILE
(NAME= emp1_dat,
FILE NAME=d:\backup\data\emp1_dat.mdf,
SIZE=4mb,
MAXSIZE=30mb,
FILEGROWTH=1mb)
Visit: www.gcreddy.com for QTP Information
To add a fi!e grou/9
To attac8 new fi!es to new fi!e grou/9
*I=?I,G TB= D4T4&4S=9
T%e information regarding t%e dataase s&c% as owner* si-e* date and time of
creation* stat&s can e viewed &sing t%e following System Stored Proced&re:
Syntax9
:5T8: T%e s)L%el)d system stored )roced&re wit%o&t a dataase name re)orts
information ao&t all t%e dataases in t%e system.
Dataase o)tions can e c%anged or dis)layed &sing:
Syntax9
Different o)tions t%at can e set to dataase are:
D5"se#nly 7 only owner of t%e dataase can &se it.
O++line 7 t%e dataase is offline w%en t%is o)tion is set.
Re')#nly 7 data can only read in t%e dataase
Sele!t int#/5"l6 !#&y 7 faster &l+ co)y
Visit: www.gcreddy.net for Testing Information
20
ALTER DATABASE emp
ADD FILEGROUP frgp1
ALTER DATABASE emp
ADD FILE
(NAME= emp2_dat,
FILE NAME=c:\mssql\emp2_dat.mdf,
SIZE=4mb,
MAXSIZE=30mb,
FILEGROWTH=1mb)
TO FILEGROUP frgp1
Sp_helpdb database name
Example:
sp_helpdb emp
Sp_dboption database name, option name, TRUE/FALSE
Visit: www.gcreddy.com for QTP Information
Sin$le "ser 7 only one &ser can &se it
83am)le:
5ena-ing t8e dataase9
T%e name of t%e dataase can e c%anged as:
Syntax9
De!eting t8e dataase9
Syntax9
T4&L=S
Tales are dataase o.ects t%at contain all t%e data in a dataase. / tale
definition is a collection of col&mns. In tales* data is organi-ed in a row'and'col&mn
format similar to a s)reads%eet. 8ac% row re)resents a &ni(&e record* and eac%
col&mn re)resents a field wit%in t%e record.
/fter yo& %ave designed t%e dataase * t%e tales t%at will store t%e data in
t%e dataase can e created. T%e data is &s&ally stored in )ermanent tales. Tales
are stored in t%e dataase files &ntil t%ey are deleted and are availale to any &ser
w%o %as t%e a))ro)riate )ermissions.
Te-/orary Ta!es
2o& can also create tem)orary tales. Tem)orary tales are similar to )ermanent
tales* e3ce)t tem)orary tales are stored in te-/d and are deleted a&tomatically
w%en no longer in &se.
Visit: www.gcreddy.net for Testing Information
21
sp_dboption emp, readonly, TRUE
sp_renamedb old name, new name
Example:
sp_renamedb emp, employee
DROP DATABASE <database name>
Example:
DROP DATABASE employee
Visit: www.gcreddy.com for QTP Information
T%e two ty)es of tem)orary tales* local and gloal* differ from eac% ot%er in t%eir
names* t%eir visiility* and t%eir availaility. Local tem)orary tales %ave a single
n&mer sign "N$ as t%e first c%aracter of t%eir namesG t%ey are visile only to t%e
c&rrent connection for t%e &serG and t%ey are deleted w%en t%e &ser disconnects
from instances of !icrosoft? SQL Server@ 6===. Cloal tem)orary tales %ave two
n&mer signs "NN$ as t%e first c%aracters of t%eir namesG t%ey are visile to any
&ser after t%ey are createdG and t%ey are deleted w%en all &sers referencing t%e
tale disconnect from SQL Server.
9or e3am)le* if yo& create a tale named e-/!oyees* t%e tale can e &sed y any
)erson w%o %as t%e sec&rity )ermissions in t%e dataase to &se it* &ntil t%e tale is
deleted. If yo& create a local tem)orary tale named Ce-/!oyees* yo& are t%e only
)erson w%o can wor+ wit% t%e tale* and it is deleted w%en yo& disconnect. If yo&
create a gloal tem)orary tale named CCe-/!oyees* any &ser in t%e dataase can
wor+ wit% t%is tale. If no ot%er &ser wor+s wit% t%is tale after yo& create it* t%e
tale is deleted w%en yo& disconnect. If anot%er &ser wor+s wit% t%e tale after yo&
create it* SQL Server deletes it w%en ot% of yo& disconnect.
Ta!e >ro/erties
2o& can define &) to 4*=6B col&mns )er tale. Tale and col&mn names m&st follow
t%e r&les for identifiersG t%ey m&st e &ni(&e wit%in a given tale* &t yo& can &se
t%e same col&mn name in different tales in t%e same dataase. 2o& m&st also
define a data ty)e for eac% col&mn.
/lt%o&g% tale names m&st e &ni(&e for eac% owner wit%in a dataase* yo& can
create m&lti)le tales wit% t%e same name if yo& s)ecify different owners for eac%.
"reating a Ta!e using =nter/rise :anager9
4. 5)en t%e 8nter)rise !anger Tool from t%e Start men&.
6. 83)and t%e server Cro&) and t%e corres)onding server.
A. 83)and t%e corres)onding dataase
B. Rig%t clic+ on Tables and select New Table item
Visit: www.gcreddy.net for Testing Information
22
Visit: www.gcreddy.com for QTP Information
E. In t%e window dis)layed enter a name to t%e col&mn* data ty)e and leng%
J. Clic+ on t%e save icon of t%e toolar to save t%e tale.
"reating a Ta!e using Query 4na!y.er9
Visit: www.gcreddy.net for Testing Information
23
Visit: www.gcreddy.com for QTP Information
,e can ma+e &se of t%e following synta3 to create a tale:
,0LL D ,6T ,0LL
/re +eywords t%at determine if n&ll val&es are allowed in t%e col&mn. :>LL is not
strictly a constraint &t can e s)ecified in t%e same manner as :5T :>LL.
D=F40LT
S)ecifies t%e val&e )rovided for t%e col&mn w%en a val&e is not e3)licitly s&))lied
d&ring an insert.
!#nst'nt7e*&ressi#n
Is a constant* :>LL* or a system f&nction &sed as t%e defa&lt val&e for t%e col&mn.
ID=,TIT@
Indicates t%at t%e new col&mn is an identity col&mn. ,%en a new row is added to t%e
tale* !icrosoft? SQL Server@ )rovides a &ni(&e* incremental val&e for t%e col&mn.
T%e ID8:TIT2 )ro)erty can e assigned to tinyint* s-a!!int* int* igint*
deci-a!(/E0)* or nu-eric(/E0) col&mns. 5nly one identity col&mn can e created
)er tale. #o&nd defa&lts and D89/>LT constraints cannot e &sed wit% an identity
col&mn. 2o& m&st s)ecify ot% t%e seed and increment or neit%er. If neit%er is
s)ecified* t%e defa&lt is "4*4$.
seed
Is t%e val&e &sed for t%e very first row loaded into t%e tale.
increment
Visit: www.gcreddy.net for Testing Information
24
CREATE TABLE tablename
(colname datatype (size) [NOT NULL | DEFAULT <constant value> |
IDENTITY(seed,increment)], colname2 ..)
Visit: www.gcreddy.com for QTP Information
Is t%e incremental val&e added to t%e identity val&e of t%e )revio&s row loaded.
=xa-/!e9
4. Select t%e corres)onding dataase in w%ic% we want to create t%e tale from
t%e availale dro) down &tton.
6. Ty)e t%e following command in t%e window.
A. clic+ on 83ec&te &tton to r&n t%e command.
=xa-/!e 29 "rating a ta!e wit8 identity co!u-n
,%en an ID8:TIT2 )ro)erty to define an identifier col&mn* consider t%at:
/ tale can %ave only one col&mn defined wit% t%e ID8:TIT2 )ro)erty
T%e seed and increment can e s)ecified. T%e defa&lt for ot% is 4
T%e identifier col&mn m&st not allow :>LL val&es and m&st not contain
D89/>LT definition
In order to insert t%e val&es e3)licitly into t%e identity col&mn * S8T
ID8:TIT2LI:S8RT o)tion is &sed.
Visit: www.gcreddy.net for Testing Information
25
CREATE TABLE dept
( dept_no int identity (10,10),
dept_name varchar(20),
location varchar(20)
)
Visit: www.gcreddy.com for QTP Information
Synta3:
D4T4T@>=S9
T%e c%oice of t%e dataty)e determines t%e +ind of data t%at can e stored
in t%e col&mn and t%e ma3im&m lengt% of data t%at can e stored in t%e
col&mn. SQL Server )rovides different ty)e of data. T%ey are:
,u-eric Dataty/es9
SQL Server )rovides many ways to store n&meric val&es* w%ic% )rovide fle3iility in
)recision* range of val&es* and data storage si-e. :&meric ty)e falls into
vario&s categories li+e intE s-a!!intE tinyintE -oneyE s-a!!-oneyE and
it. To store decimal val&es dataty)es li+e f!oatErea!E deci-a! and
nu-eric are &se.
Bigint is t%e new dataty)e in SQL Server 6=== &nder t%is category.
"8aracter Dataty/e9
T%ere are t%ree valid dataty)es for storing strings. T%ey are:
"8ar9 t%is is &sed for storing fi3ed'lengt% strings. Col&mns defined as c%ar will store
lan+s to fill o&t a fi3ed n&mer of c%aracters. T%e ma3im&m lengt% of a
c%aracter col&mn is F=== ytes.
*arc8ar9 t%is is &sed for storing v'ri'5le len$t8 strin$s. Col&mns defined as varc%ar
will tr&ncate lan+s to save s)ace.
Text9 t%is is &sed for storing of virt&ally &nlimited si-e"&)to 6 gigaytes of te3t )er
row.
&inary Dataty/es9
Visit: www.gcreddy.net for Testing Information
26
SET IDENTITY_INSERT tablename ON | OFF
Visit: www.gcreddy.com for QTP Information
T%ese dataty)es store strings consisting of inary val&es.i.e* %a3adecima
n&mers instead of c%aracters. T%ey are:
&inary9 Stores inary data of fi3ed leng% wit% a ma3im&m leng% of F*=== ytes
*arinary9 Stores variale leng% inary data wit% a ma3im&m lengt% of F*=== ytes
I-age9 SQL Server )rovides a mec%anism for storing inary data more t%an F===
ytes &sing image dataty)es. 9or 83am)le* t%e )%otogra)% of t%e
em)loyees can e stored.
DateTi-e Dataty/e9
SQL Server enales to store date and time val&es. Col&mns &sing
dateti-e or s-a!!dateti-e will store ot% date and time.
0nicode Dataty/e9
>nicode standard incl&des all t%e c%aracters t%at are defined in t%e vario&s
c%aracter sets. >sing >nicode data ty)es* a col&mn can store any c%aracter
t%at is defined y t%e >nicode standard. >nicode data is stored &sing
nc8arE nvarc8arE ntext dataty)es.
S/ecia! DataTy/es9
"ursorETi-eSta-/E 0niFue Identifier and &itG
,ew Dataty/es9
SQL Server 6=== introd&ces t8ree new data ty)es. igint is an F'yte integer ty)e.
sF!Hvariant is a ty)e t%at allows t%e storage of data val&es of different
data ty)es. ta!e is a ty)e t%at allows a))lications to store res&lts
tem)orarily for later &se. It is s&))orted for variales* and as t%e ret&rn
ty)e for &ser'defined f&nctions
:odifying Ta!es
Visit: www.gcreddy.net for Testing Information
27
Visit: www.gcreddy.com for QTP Information
/fter a tale is created* yo& can c%ange many of t%e o)tions t%at were defined for
t%e tale w%en it was originally created* incl&ding:
Col&mns can e added* modified* or deleted. 9or e3am)le* t%e col&mn name*
lengt%* data ty)e* )recision* scale* and n&llaility can all e c%anged*
alt%o&g% some restrictions e3ist. 9or more information.
PRI!/R2 H82 and 95R8IC: H82 constraints can e added or deleted.
>:IQ>8 and C<8CH constraints and D89/>LT definitions "and o.ects$ can e
added or deleted.
/n identifier col&mn can e added or deleted &sing t%e ID8:TIT2 or
R5,C>IDC5L )ro)erty.
5ena-ing a Ta!e
5ena-ing a "o!u-n9
Syntax for 4LT=5 T4&L= co--and9
Visit: www.gcreddy.net for Testing Information
28
ALTER TABLE tablename
ADD columnName datatype [not null |identity|default]
|ALTER COLUMN <column specifcations>
|DROP COLUMN columnName
|ADD CONSTRAINT constraintName {CHECK(..) | UNIQUE | PRIMARY KEY..}
|DROP CONSTRAINT constraintName
Syntax:
SP_RENAME <old_tableName>,<new_tableName>
Example:
SP_RENAME employee.emp
Syntax:
SP_RENAME < tableName.columnname>,<newcolName>
Example:
SP_RENAME emp.basic_salary,bsal
Visit: www.gcreddy.com for QTP Information
=xa-/!es9
"8anging dataty/e
"8anging ,0LLs
4dding "o!u-ns
S/H8e!/9
T%is System Stored Proced&re is &sed to )rovide descri)tion ao&t t%e tale
str&ct&re.
83am)le:
Inserting *a!ues in a Ta!e
T%e Insert command is &sed to add rows to a tale. T%e data entered in t%e
tale s%o&ld matc% t%e order of t%e col&mns as t%ey a))ear in t%e tale.
Syntax9
=xa-/!e9
Visit: www.gcreddy.net for Testing Information
29
ALTER TABLE emp ALTER COLUMN emp_no varchar(5)
ALTER TABLE emp ALTER COLUMN emp_no varchar(5) not null
ALTER TABLE emp ADD doj datetime
SP_HELP emp
INSERT <table_name> (column_list) VALUES (data_list)
INSERT emp
VALUES(E001,sam,10,B,4500,11/3/96)
Visit: www.gcreddy.com for QTP Information
,%en only t%e date is s)ecified in t%e datetime dataty)e* t%e time is incl&ded
as ==:== /! y defa&lt.
If we want to insert only certain col&mns data into t%e tale* t%e col&mn
names %ave to e s)ecified.
=xa-/!e9
Data :ani/u!ation
To modify t%e val&es stored in a tale* >PD/T8 statement is &sed.
=xa-/!e9 t%e em)loyee name Sam&el wit% t%e em)Lno 08==41 was wrongly entered
as Sam in t%e tale. To correct it* t%e following statement is &sed.
De!eting data fro- a Ta!e9
To remove rows from a tale* D8L8T8 or TR>:C/T8 statements can e &sed.
To delete a )artic&lar row from t%e tale we %ave to &se D8L8T8 command.
To delete all rows from t%e tale* TR>:C/T8 command can also e &sed.
Visit: www.gcreddy.net for Testing Information
30
INSERT emp ( emp_no,emp_name)
VALUES(E004,Sammy)
UPDATE emp
SET emp_name=Samuel
WHERE emp_no=E001
Syntax:
DELETE FROM tablename WHERE condition
Example:
DELETE FROM emp WHERE emp_no=E002
Syntax:
TRUNCATE TABLE tablename
Example:
TRUNCATE TABLE emp
Visit: www.gcreddy.com for QTP Information
T%e TR>:C/T8 statement removes t%e w%ole tale at a time. ,%ereas
t%e delete tale command removes eac% row from t%e tale one y one. T%is is m&c%
faster t%an a D8L8T8 statement* es)ecially on large tales.
To remove t%e tale along wit% t%e str&ct&re* DR5P statement is &sed.
5etrieva! of Data9
To retrieve data from a dataase o.ect* S8L8CT statement is &sed.
Syntax9
=xa-/!e9
D4T4 I,T=G5IT@
It is very im)ortant for t%e data in a dataase to e acc&rate* consistent and reliale.
T%is im)lies t%at it is very cr&cial to enforce data integrity.
Data integrity ens&res t%e consistency and correctness of data stored in a dataase.
It is roadly classified into t%e following fo&r categories.
=ntity integrity 7 ens&res t%at eac% row in a tale is &ni(&e. It enforces
integrity of t%e data contained in t%e col&mns* w%ic% &ni(&ely identify t%e
rows in a tale.
Do-ain integrity 7 ens&res t%at only valid ranges of val&es are allowed to
e stored in a col&mn. It can e enforced* y restricting t%e ty)e of data* t%e
range of val&es and t%e format of t%e data.
5eferentia! integrity 7 ens&res t%at t%e data in t%e dataase remains
&niformly consistent* acc&rate and &sale even after t%e data in it %as een
c%anged. It maintains t%e integrity of data y ens&ring t%at t%e c%anges
made in t%e )arent tale are also reflected in all t%e de)endent tales.
Visit: www.gcreddy.net for Testing Information
31
Syntax:
DROP TABLE tablename
Example:
DROP TABLE dept1
SELECT <column_list> FROM <table_name> WHERE <condition>
1.SELECT * FROM emp
2.SELECT emp_no,emp_name
FROM emp
WHERE dept_no=10
Visit: www.gcreddy.com for QTP Information
0ser defined integrity 7 refers to a set of r&les s)ecified y a &ser* w%ic%
do not elong to t%e entity* domain and referential integrity categories.
=,F65"I,G D4T4 I,T=G5IT@
Incor)orating &siness r&les and s)ecifying t%e relevant constraints can
enforce data integrity.
#&siness r&les refer to s)ecific )olicies followed y an organi-ation for t%e smoot%
r&nning of its &siness. #&siness r&les ens&re t%at t%e dataase stores acc&rate data
in relation to t%e &siness )olicies.
9or e3am)le an organi-ation may %ave a )ersonnel )olicy* w%ic% states t%at t%e
minim&m salary of an em)loyee is OE==. T%is is a &siness r&le.
Constraints refer to r&les* w%ic% restrict t%e val&es t%at are inserted in t%e col&mns
of a tale.
"6,ST54I,TS9
/ Constraint can eit%er e created at t%e time of creating a tale or can e added
later. ,%en a constraint is created after tale creation* it c%ec+s t%e e3isting data. If
t%e e3isting data does not conform to t%e r&le eing enforced y t%e constraint* t%en
t%e constraint is re.ected.
/ constraint can e created &sing eit%er of t%e following statements:
CR8/T8 T/#L8 statement.
/LT8R T/#L8 statement.
0sing "5=4T= T4&L= state-ent9
/ constraint can e defined on a col&mn at t%e time of creating a tale. It can e
created wit% t%e CR8/T8 T/#L8 statement:
T8e syntax is 9
0sing 4LT=5 T4&L= state-ent9
/ constraint can also e defined on a col&mn after a tale %as een created. T%is can
e done &sing t%e /LT8R T/#L8 statement.
Visit: www.gcreddy.net for Testing Information
32
CREATE TABLE table name
"Col&mn:ame4 dataty)e C5:STR/I:T contraintLname constraintLty)e*
Col&mnname6 data ty)e PPP.$
Visit: www.gcreddy.com for QTP Information
T8e syntax is9
T@>=S 6F "6,ST54I,TS
T%e following are t%e different ty)es of Constraints:
C<8CH constraint
>:IQ>8 H82 constraint
PRI!/R2 H82 constraint
95R8IC: H82 constraint
"B="I "6,ST54I,T

/ C<8CH constraint enforces domain integrity y restricting t%e val&es to e
inserted in a col&mn. It allows only valid val&es in a col&mn.
It is )ossile to define m&lti)le C<8CH constraints on a single col&mn.
Syntax9
=xa-/!e9
T%e r&les regarding t%e creation of C<8CH constraint are as follows:
It can e created at t%e col&mn level as well as tale level.
It is &sed to limit t%e val&es t%at can e inserted into a col&mn.
It can contain &ser's)ecified searc% conditions.
It cannot contain s& (&eries. / s& (&ery is one or more select
statements emedded wit%in anot%er select statement.
Visit: www.gcreddy.net for Testing Information
33
ALTER TABLE table name
/DD C5:STR/I:T constraintLname constraintLty)e "field:ame$
CREATE TABLE table_name
(colName datatype CONSTRAINT const_name CHECK(<criteria>), colName2
..)
CRAETE TABLE Location
"LocLid int* City varc%ar"4E$ C5:STR/I:T c%+Lcity C<8CH" city in "QR #8RH8L82R*
Q#5ST5:R* QC<IC/C5R* QD/LL/SR* Q!>:C<8:R* Q:8, 25RHR* QP/RISR* Q,/S<I:CT5:R*$
Visit: www.gcreddy.com for QTP Information
It does not c%ec+ t%e e3isting data into t%e tale if created wit% t%e N#
C8e!6 O&ti#n.
It can reference ot%er col&mns of t%e same tale.
0,IQ0= "6,ST54I,T
>:IQ>8 constraints are &sed to enforce &ni(&eness on non')rimary +ey
col&mns.
/ /ri-ary 2ey constraint col&mn a&tomatically incl&des a restriction for
&ni(&eness. <owever a &ni(&e constraint allows n&ll val&es.
It is not advisale to %ave col&mns wit% n&ll val&es* t%o&g% t%ese are allowed.
/ n&ll val&e is also validated* %ence t%ere can only e one record in t%e tale wit% a
n&ll val&e. T%e tale canRt contain anot%er row wit% n&ll val&e.
9or e3am)le:
T%e r&les regarding t%e creation of >:IQ>8 constraint are:
It does not allow two rows to %ave t%e same non'n&ll val&es in a tale.
It gets enforced a&tomatically w%en a >:IQ>8 inde3 is created.
!&lti)le >:IQ>8 constraints can e )laced on a tale.
>5I:45@ I=@ constraint9
/ )rimary +ey constraint is defined on a col&mn or a set of col&mns w%ose val&es
&ni(&ely identify t%e rows in a tale. T%ese col&mns are referred to as )rimary +ey
col&mns. / )rimary +ey col&mn cannot contain :>LL val&es since it is &sed to
&niF(&ely identify rows in a tale.
,%ile defining a PH constraint* yo& need to s)ecify a name for t%e constraint. If no
name is s)ecified* SQL Server a&tomatically assigns a &ni(&e name to t%e constraint.
/ny col&mn or set of col&mns t%at &ni(&ely identifies a row in a tale can e a
candidate for t%e )rimary +ey. T%ese set of col&mns are referred to as candidate
+eys. 5ne of t%e candidate +eys is c%osen to e t%e )rimary +ey* ased on familiarity
and greater &sage. T%e ot%er +ey* w%ic% is not c%osen as t%e )rimary +ey is called as
alternate +ey.
Syntax9
Visit: www.gcreddy.net for Testing Information
34
ALTER TABLE AUTHOUR
ADD CONSTRAINT unq_ta UNIQUE (title_id, au_id)
CREATE TABLE table name
(ColumnName1 datatype CONSTRAINT ont!a"nt#name $!"ma!y %ey& Columnname2
data type '''()
OR
ALTER TABLE table name
ADD CONSTRAINT constraint_name PRIMARY KEY (feld name)
Visit: www.gcreddy.com for QTP Information
=xa-/!e9
"L0ST=5=D 4,D ,6, "L0ST=5=D I,D=J
/n inde3 is a dataase o.ect w%ic% )rovides faster access to data y searc%ing t%e
data &sing t%e +ey val&es. ,%en an inde3 is created on a tale* t%e data in t%e tale
is sorted ased on t%e +ey val&e on w%ic% t%e inde3 is created.
S(l server )rovides two ty)es of inde3es:
Cl&stered inde3
:on cl&stered inde3
In a cl&stered inde3 t%e data is )%ysically sorted* as a res&lt* only one cl&stered
inde3 is )ossile )er tale. / cl&stered inde3 c%anges t%e )%ysical order of t%e rows.
T%erefore* it is advisale to create a cl&stered inde3 efore a non'cl&stered inde3 so
t%at t%e non cl&stered inde3 is not re&ilt. / cl&stered inde3 is faster in )erformance
in com)arison to a con cl&stered inde3.
<ence a cl&stered inde3 is one in w%ic% t%e logical order of t%e inde3 is same as t%e
)%ysical sorted order of t%e corres)onding rows t%at e3ist in a tale.
/ non'cl&stered inde3 is a se)arate inde3 str&ct&re inde)endent of t%e )%ysical sort
order of t%e data in t%e tale. /s s&c%* t%e data rows may e randomly )laced in t%e
tale.
<ence a non'cl&stered inde3 one in w%ic% t%e logical order of t%e inde3 does not
matc% t%e )%ysical sort order of t%e rows on dis+.
If a col&mn %as a PRI!/R2 H82 constraint wit% a cl&stered inde3 defined on it* t%en
t%e constraint needs to e dro))ed efore a new constraint is defined on t%e col&mn
Visit: www.gcreddy.net for Testing Information
35
CREATE TABLE emp
(empcode int CONSTRAINT pk_const PRIMARY KEY,
name char (20),
designation char(20),
salary int not null)
OR
ALTER TABLE emp
ADD CONSTRAINT pk_const PRIMARY KEY (empcode)
Visit: www.gcreddy.com for QTP Information
It creates &ni(&e cl&stered inde3 y defa&lt
It cannot e created on col&mns t%at %ave een defined as :>LL d&ring tale
creation
It can e created only once for a tale* t%at is only )rimary +ey constraint can
e created )er tale
It always c%ec+s for e3isting data even if it is created wit% t%e ,IT< :5
C<8CH 5PTI5:
,%en a PH constraint is created a &ni(&e cl&stered inde3 gets created a&tomatically.
T%e inde3 cannot e dro))ed e3)licitly. It is dro))ed only w%en t%e tale or t%e
constraint is dro))ed. If a cl&stered inde3 already e3ists* t%en t%e PH constraint gets
re.ected.l
Foreign 2ey constraints
/ foreign +ey is a col&mn or comination of col&mns w%ose val&es matc% t%e
)rimary +ey of anot%er tale.
/ foreign +ey does not %ave to e &ni(&e. <owever* foreign +ey val&es m&st
e co)ies of t%e )rimary +ey val&es of t%e master tale.
/ foreign +ey is a col&mn on w%ic% a F65=IG, I=@ constraint %as
een defined. / 95R8IC: H82 constraint associates one or more col&mns of a tale
wit% an identical set of col&mns on w%ic% a PRI!/R2 H82 constraint %as een defined
")rimary +ey col&mn$ in anot%er tale./ foreign +ey may refer to t%e )rimary +ey of
anot%er tale or same tale.
Syntax9
9or =xa-/!e:
T%e r&les regarding t%e creation of a 95R8IC: H82 constraint are as follows:
T%e no.of col&mns s)ecified in t%e foreign +ey statement m&st matc% t%e
no.of col&mns in t%e references cla&se and m&st e s)ecified in t%e same
order.
Visit: www.gcreddy.net for Testing Information
36
CREATE TABLE table_name
(colName datatype CONSTRAINT const_name REFERENCES
parent_Table(primary key column),colName2..)
(or)
ALTER TABLE table_name
ADD CONSTRAINT const_name REFERENCES parent_Table(primarykey
column)
ALTER TABLE dept
ADD CONSTRAINT fk_ecode FOREIGN KEY (e_code) REFERENCES
EMPLOYEES(e_code)
Visit: www.gcreddy.com for QTP Information
T%e foreign +ey can reference t%e )rimary +ey or a >:IQ>8 constraint of
anot%er tale.
T%e foreign +ey constraint t%at is created &sing t%e ,IT< :5C<8CH o)tion
will )revent t%e foreign +ey constraint from validating e3isting data.
D56>>I,G "6,ST54I,TS9
/ constraint can e dro))ed &sing t%e alter tale statement in t%e (&ery analy-er.
T%e synta3 of t%e /LT8R T/#L8 statement for dro))ing a constraint isG
Dro)s t%e constraint* conLcity* defined on t%e city col&mn of t%e )&lis%ers tale.
/ll t%e constraints defined on a tale are dro))ed a&tomatically w%en t%e tale is
dro))ed.
"6,ST54I,TS 4,D T5IGG=5S9
8ac% category of data integrity is est enforced t%ro&g% t%e following
constraints.
8ntity integrity is est enforced t%ro&g% t%e PRI!/R2 H82 constraint* >:IQ>8
constraint and t%e ID8:TIT2 )ro)erty.
T%e ID8:TIT2 )ro)erty creates an identity col&mn in t%e tale. /n identity col&mn is
a )rimary +ey col&mn for w%ic% n&meric val&es are generated a&tomatically. 8ac%
generated val&e is different from t%e )revio&s val&e* t%&s ens&ring &ni(&eness of
data in eac% row at t%e tale. T%e ID8:TIT2 )ro)erty also ens&res t%at w%ile
inserting data* t%e &ser need not e3)licitly insert a val&e for t%e identity col&mn.
Domain integrity is est enforced t%ro&g% t%e D89/>LT constraint* C<8CH constraint
and t%e 95R8IC< H82 constraint.
Referential integrity is est enforced t%ro&g% t%e 95R8IC: H82 constraint and t%e
c%ec+ constraint.
>ser'defined integrity is est enforced t%ro&g% all col&mn and tale level constraints
t%at are s)ecified wit% t%e CR8/T8 T/#L8 constraint.
50L=S 4,D D=F40LTS
R&les and defa&lts are o.ects* w%ic% %el) enforce t%e data integrity. T%ese o.ects
are o&nd to col&mns or &ser defined data ty)es to ens&re t%at only valid val&es are
allowed to insert into t%e tales.
Visit: www.gcreddy.net for Testing Information
37
ALTER TABLE table_name
DROP CONSTRAINT constraint_name
For example:
ALTER TABLE publishers
DROP CONSTRAIANT con_city
Visit: www.gcreddy.com for QTP Information
5u!es
/ r&le )rovides a mec%anism for enforcing domain constraints for col&mns or
&ser defined data ty)es. T%e r&le is a))lied efore any modification is to e done on
t%e tale. In ot%er words* a r&le s)ecifies t%e restriction on t%e val&es for a col&mn
or a &ser defined data ty)e.
T%e synta3 of t%e CR8/T8 R>L8 statement is:
!ore 83am)les:
CR8/T8 R>L8 de)tLnameLr&le
/S Sde)tname :5T I: "Qacco&ntsR*RstoresR$
CR8/T8 R>L8 ma3L)riceLr&le
/S Sma3)rice KTOE===
CR8/T8 R>L8 em)LcodeLr&le
/S Sem)code LIH8 QU9'!VU/'MV
Information on a r&le can e otained &sing t%e s/H8e!/ system stored )roced&re.
T%e te3t of a r&le can e dis)layed &sing t%e s/H8e!/text system stored )roced&re
wit% t%e name of t%e r&le as its )arameter.
&inding 5u!es
/ r&le can e o&nd &sing t%e s/Hindru!e system stored )roced&re.
Syntax9
#inds t%e r&le* ty)eLr&le*to t%e ty)e col&mn of t%e titles tale
T%e restrictions on t%e &se of t%e r&les are as follows:

5nly one r&le can e o&nd to a col&mn or a &ser defined dataty)e.
Visit: www.gcreddy.net for Testing Information
38
CREATE RULE rule_name
AS conditional_expression.
For example:
CREATE RULE type_rule
AS @typerule IN(business,mod_cook, trad_cook, popular_comp, psychology)
Sp_bindrule rule_name, object_name.ColName
For example:
Sp_bindrule type_rule, titles.type
Visit: www.gcreddy.com for QTP Information
/ r&le cannot e o&nd to system dataty)es.
If a new r&le is o&nd to a col&mn or dataty)e t%at is already een inserted
in t%e tale* t%e e3isting val&es in t%e tales do not %ave to meet t%e criteria
s)ecified y t%e r&le.
/ r&le cannot e defined for a system'defined dataty)e
0ninding 5u!es
/ r&le can e &no&nd from a col&mn or &ser'defined dataty)e &sing t%e
s)L&nindr&le system stored )roced&re.
T%e synta3 of t%e s)L&nindr&le is:

>ninds t%e r&le attac%ed to t%e ty)e col&mn of t%e titles tale.
D=F40LTS

Defa&lt is a constant val&e assigned to a col&mn* into w%ic% t%e &ser need
not insert val&es./ defa&lt can e o&nd to a col&mn or a &ser'defined dataty)e.
T%e synta3 of t%e CR8/T8 D89/>LT statement is:
/ny constant* &ilt'in f&ntion* mat%ematical e3)ression or a gloal variale
can e &sed in t%e constant e3)ression. T%e c%aracter and date constants m&st e
incl&ded in single (&otation mar+s "Q$* w%ereas money* integer* and floating')oint
constants can e s)ecified wit%o&t (&otation mar+s.

&inding Defau!ts
T%e s/Hindefau!t system stored )roced&re is &sed for inding a defa&lt.
T%e synta3 of s)Lindefa&lt is:
Creates a defa&lt* cityLdefa&lt* and inds t%e defa&lt val&e* 5a+land* to city col&mn
of t%e a&t%ors tale.
T%e statement
Visit: www.gcreddy.net for Testing Information
39
S/Hunindru!e o.ectLname
9or e3am)le:
S/Hunindingru!e Qtitles.ty)eR
CREATE DEFAULT default_name
As constant_expression
Sp_bindefault default _name_, object_name.ColName
For example:
1.CREATE DEFAULT city_default AS Oakland
2. Sp_default city_default, authors.city
S/Hindefau!t cityLdefa&lt* cityLdataty)e.
Visit: www.gcreddy.com for QTP Information

#inds t%e defa&lt cityLdefa&lt to t%e &ser'defined dataty)e* cityLdataty)e.
0,&I,DI,G D=F40LTS
Defa&lts can e &no&nd from a col&mn or &ser defined dataty)e &sing t%e
s/Hunindefau!t system stored )roced&re.
T%e synta3 of s)L&nindefa&lt is:

>ninds t%e defa&lt s)ecified on t%e city col&mn of t%e a&t%ors tale.
5=,4:I,G 50L=S 4,D D=F40LTS

T%e s/Hrena-e system stored )roced&re can e &sed for renaming r&les
and defa&lts.
T%e synta3 of s)Lrename is:
D56>>I,G 50L=S 4,D D=F40LTS

T%e DR5P R>L8 and DR5P D89/>LT statement can e &sed to dro) a r&le and
defa&lt res)ectively./ r&le or defa&lt m&st e &no&nd from t%e col&mn or t%e &ser'
defined dataty)e efore it is dro))ed.
T%e synta3 for dro))ing a r&le is:
,%ere r&leLname is t%e name of t%e r&le to e dro))ed.
T%e synta3 for dro))ing a defa&lt is :
Visit: www.gcreddy.net for Testing Information
40
Sp_unbindefault object_name
For example:
Sp_unbindefault authors.city
Sp_rename old_object_name, new_object_name
DROP RULE rule_name
DROP DEFAULT default_name
Visit: www.gcreddy.com for QTP Information

,%ere defa&ltLname is t%e name of t%e defa&lt to e dro))ed.

$6I,S
#y &sing .oins* yo& can retrieve data from two or more tales ased on logical
relations%i)s etween t%e tales. Woins indicate %ow !icrosoft? SQL Server@ 6===
s%o&ld &se data from one tale to select t%e rows in anot%er tale.
/ .oin condition defines t%e way two tales are related in a (&ery y:
S)ecifying t%e col&mn from eac% tale to e &sed for t%e .oin. / ty)ical .oin
condition s)ecifies a foreign +ey from one tale and its associated +ey in t%e
ot%er tale.
S)ecifying a logical o)erator "T* XK* and so on$ to e &sed in com)aring
val&es from t%e col&mns.
Woins can e s)ecified in eit%er t%e 9R5! or ,<8R8 cla&ses. T%e .oin conditions
comine wit% t%e ,<8R8 and </VI:C searc% conditions to control t%e rows t%at are
selected from t%e ase tales referenced in t%e 9R5! cla&se.
Visit: www.gcreddy.net for Testing Information
41
Visit: www.gcreddy.com for QTP Information
S)ecifying t%e .oin conditions in t%e 9R5! cla&se %el)s se)arate t%em from any
ot%er searc% conditions t%at may e s)ecified in a ,<8R8 cla&se* and is t%e
recommended met%od for s)ecifying .oins. / sim)lified SQL'D6 9R5! cla&se .oin
synta3 is:
9#in7ty&e s)ecifies w%at +ind of .oin is )erformed: an inner* o&ter* or cross .oin.
:#in7!#n)iti#n defines t%e )redicate to e eval&ated for eac% )air of .oined rows. T%is
is an e3am)le of a 9R5! cla&se .oin s)ecification:
/lt%o&g% .oin conditions &s&ally %ave e(&ality com)arisons "T$* ot%er com)arison or
relational o)erators can e s)ecified* as can ot%er )redicates
,%en SQL Server )rocesses .oins* t%e (&ery engine c%ooses t%e most efficient
met%od "o&t of several )ossiilities$ of )rocessing t%e .oin. /lt%o&g% t%e )%ysical
e3ec&tion of vario&s .oins &ses many different o)timi-ations* t%e logical se(&ence is:
T%e .oin conditions in t%e 9R5! cla&se are a))lied.
T%e .oin conditions and searc% conditions from t%e ,<8R8 cla&se are a))lied.
T%e searc% conditions from t%e </VI:C cla&se are a))lied.
Ty/es of $oins
Woin conditions can e s)ecified in eit%er t%e 9R5! or ,<8R8 cla&sesG s)ecifying
t%em in t%e 9R5! cla&se is recommended. ,<8R8 and </VI:C cla&ses can also
contain searc% conditions to f&rt%er filter t%e rows selected y t%e .oin conditions.
Woins can e categori-ed as:
Inner .oins "t%e ty)ical .oin o)eration* w%ic% &ses some com)arison o)erator
li+e T or XK$. T%ese incl&de e(&i'.oins and nat&ral .oins.
Inner .oins &se a com)arison o)erator to matc% rows from two tales ased
on t%e val&es in common col&mns from eac% tale. 9or e3am)le* retrieving all
rows w%ere t%e st&dent identification n&mer is t%e same in ot% t%e
students and courses tales.
5&ter .oins. 5&ter .oins can e a left* a rig%t* or f&ll o&ter .oin.
Visit: www.gcreddy.net for Testing Information
42
SELECT columnList
FROM frst_table join_type second_table [ON (join_condition)]
Visit: www.gcreddy.com for QTP Information
5&ter .oins are s)ecified wit% one of t%e following sets of +eywords w%en t%ey
are s)ecified in t%e 9R5! cla&se:
L89T W5I: or L89T 5>T8R W5I:
T%e res&lt set of a left o&ter .oin incl&des all t%e rows from t%e left
tale s)ecified in t%e L89T 5>T8R cla&se* not .&st t%e ones in w%ic%
t%e .oined col&mns matc%. ,%en a row in t%e left tale %as no
matc%ing rows in t%e rig%t tale* t%e associated res&lt set row contains
n&ll val&es for all select list col&mns coming from t%e rig%t tale.
RIC<T W5I: or RIC<T 5>T8R W5I:.
/ rig%t o&ter .oin is t%e reverse of a left o&ter .oin. /ll rows from t%e
rig%t tale are ret&rned. :&ll val&es are ret&rned for t%e left tale any
time a rig%t tale row %as no matc%ing row in t%e left tale.
9>LL W5I: or 9>LL 5>T8R W5I:.
/ f&ll o&ter .oin ret&rns all rows in ot% t%e left and rig%t tales. /ny
time a row %as no matc% in t%e ot%er tale* t%e select list col&mns
from t%e ot%er tale contain n&ll val&es. ,%en t%ere is a matc%
etween t%e tales* t%e entire res&lt set row contains data val&es from
t%e ase tales.
Cross .oins.
Cross .oins ret&rn all rows from t%e left tale* eac% row from t%e left tale is
comined wit% all rows from t%e rig%t tale. Cross .oins are also called
Cartesian )rod&cts.
"ase Study9
,%en yo& loo+ at t%e e3am)le tales elow* notice t%at:
T%e Y8m)loyeeLIDY col&mn is t%e )rimary +ey of t%e Y8m)loyeesY tale
T%e YProdLIDY col&mn is t%e )rimary +ey of t%e Y5rdersY tale
T%e Y8m)loyeeLIDY col&mn in t%e Y5rdersY tale is &sed to refer to t%e
)ersons in t%e Y8m)loyeesY tale wit%o&t &sing t%eir names
=-/!oyees:
=-/!oyeeHID ,a-e
=4 <ansen* 5la
Visit: www.gcreddy.net for Testing Information
43
Visit: www.gcreddy.com for QTP Information
=6 Svendson* Tove
=A Svendson* Ste)%en
=B Pettersen* Hari
6rders9
>rodHID >roduct =-/!oyeeHID
6AB Printer =4
JEI Tale =A
FJE C%air =A
0sing $oins
=xa-/!e I,,=5 $6I,
Syntax
S8L8CT field4* field6* fieldA
9R5! firstLtale
I::8R W5I: secondLtale
5: firstLtale.+eyfield T secondLtale.foreignL+eyfield
,%o %as ordered a )rod&ct* and w%at did t%ey orderZ
S8L8CT 8m)loyees.:ame* 5rders.Prod&ct
9R5! 8m)loyees
I::8R W5I: 5rders
5: 8m)loyees.8m)loyeeLIDT5rders.8m)loyeeLID
T%e I::8R W5I: ret&rns all rows from ot% tales w%ere t%ere is a matc%. If t%ere
are rows in 8m)loyees t%at do not %ave matc%es in 5rders* t%ose rows will not e
listed.
5esu!t
,a-e >roduct
<ansen* 5la Printer
Svendson* Ste)%en Tale
Svendson* Ste)%en C%air
=xa-/!e L=FT $6I,
Syntax
S8L8CT field4* field6* fieldA
9R5! firstLtale
L89T W5I: secondLtale
5: firstLtale.+eyfield T secondLtale.foreignL+eyfield
Visit: www.gcreddy.net for Testing Information
44
Visit: www.gcreddy.com for QTP Information
List all em)loyees* and t%eir orders ' if any.
S8L8CT 8m)loyees.:ame* 5rders.Prod&ct
9R5! 8m)loyees
L89T W5I: 5rders
5: 8m)loyees.8m)loyeeLIDT5rders.8m)loyeeLID
T%e L89T W5I: ret&rns all t%e rows from t%e first tale "8m)loyees$* even if t%ere are
no matc%es in t%e second tale "5rders$. If t%ere are rows in 8m)loyees t%at do not
%ave matc%es in 5rders* t%ose rows a!so will e listed.
5esu!t
,a-e >roduct
<ansen* 5la Printer
Svendson* Tove
Svendson* Ste)%en Tale
Svendson* Ste)%en C%air
Pettersen* Hari
=xa-/!e 5IGBT $6I,
Syntax
S8L8CT field4* field6* fieldA
9R5! firstLtale
RIC<T W5I: secondLtale
5: firstLtale.+eyfield T secondLtale.foreignL+eyfield
List all orders* and w%o %as ordered ' if any.
S8L8CT 8m)loyees.:ame* 5rders.Prod&ct
9R5! 8m)loyees
RIC<T W5I: 5rders
5: 8m)loyees.8m)loyeeLIDT5rders.8m)loyeeLID
T%e RIC<T W5I: ret&rns all t%e rows from t%e second tale "5rders$* even if t%ere
are no matc%es in t%e first tale "8m)loyees$. If t%ere %ad een any rows in 5rders
t%at did not %ave matc%es in 8m)loyees* t%ose rows a!so wo&ld %ave een listed.
5esu!t
,a-e >roduct
<ansen* 5la Printer
Svendson* Ste)%en Tale
Svendson* Ste)%en C%air
Visit: www.gcreddy.net for Testing Information
45
Visit: www.gcreddy.com for QTP Information
=xa-/!e
,%o ordered a )rinterZ
S8L8CT 8m)loyees.:ame
9R5! 8m)loyees
I::8R W5I: 5rders
5: 8m)loyees.8m)loyeeLIDT5rders.8m)loyeeLID
,<8R8 5rders.Prod&ct T [Printer[
5esu!t
,a-e
<ansen* 5la
Se!f $oin9
Woining a tale to it self is called as self .oin. In a self'.oin* we %ave to &se two
co)ies of t%e same tale twice. To disting&is% etween t%e two co)ies we %ave to &se
d&)licate names to t%e tales called as tale aliases.
=xa-/!e9
Cet t%e em)loyees and corres)onding manager names from t%e following
emp tale. In t%is tale $ri) filed refers t%e id of t%e manager for t%e em)loyee.
T%ese are not%ing &t e&i)3s. It means* any one of t%e em)loyees will ecome t%e
manager for ot%er em)loyee.
=:>
=-/id =-/na-e -grid
4== /nil 4=B
4=4 #al& 4=A
4=6 Santos% 4==
4=A Vive+ 4=B
4=B Wagan 4=6
BUILT IN FUNCTIONS
SQL Server 6=== )rovides a lot of f&nctions* w%ic% can e &sed as calc&lated
fields as )art of col&mn lists in a S8L8CT statement. S&c% f&nctions are called as
#&ilt'in 9&nctions.
4rit8-etic o/erators
Visit: www.gcreddy.net for Testing Information
46
SELECT a.empid,a.empname,a.mgrid,b.empname ManagerName FROM
EMP a INNER JOINEMP b
ON a.mgrid=b.empid
Visit: www.gcreddy.com for QTP Information
T%e arit%metic o)erators s&))orted y SQL server are:
\ for addition
' for s&traction
/ for division
] for m&lti)lication
^ for mod&lo
T%e #)"l# arit%metic o)erator is &sed to otain t%e remainder of two divisile
n&meric integer val&es. It cannot e &sed wit% money data ty)e col&mns.
/ll t%e arit%metic o)erators can e &sed in t%e S8L8CT list wit% t%e col&mn names
and n&meric constants in a comination.
83am)le:
,%en any arit%metic o)eration is )erformed on a :>LL val&e* t%e res&lt is always
:>LL eca&se :>LL val&es %ave no e3)licitly assigned val&es. /rit%metic o)erations
can e )erformed on more t%an one col&mn at a time. Consider t%e following (&ery
code:
T%e aove (&ery com)&tes t%e )rod&ct of ytdLsales and )rice from t%e titles tale
and dis)lays t%e o&t)&t wit% t%e &ser'defined %eadings.
Some r&les regarding t%e &sage of arit%metic o)erators are:
/rit%metic o)erations can e )erformed on n&meric col&mns or n&meric
constants.
T%e mod&lo "^$ o)erator cannot e &sed wit% col&mns of money*
smallmoney* float or real dataty)es.
T%e synta3 is:
SELECT function_name(parameters)
String functions )rovided y SQL server.
F0,"TI6, D=S"5I>TI6,
83)ression\e3)ressionU\e3)ressionV Concatenates two or more c%aracter or
inary strings.
/SCII "c%aracterLe3)ression$ Ret&rns t%e /SCII val&e of t%e
c%aracater e3)ression
Visit: www.gcreddy.net for Testing Information
47
SELECT title_id, price, price+5, ytd_sales*5 FROM titles.
SELECT Title_Id=title_id, sValue=ytd_sales*price FROM tiles
Visit: www.gcreddy.com for QTP Information
C</R "integerLe3)ression$ Ret&rns t%e c%aracter e(&ivalent of t%e
/SCII code val&e.
C</RI:D8;"Q)atternR* e3)ression$ Ret&rns t%e starting )osition of t%e
s)ecified )attern.
DI998R8:C8 "c%aracterLe3)ression4*
c%aracterLe3)ression6$
Com)ares two straing and eval&ates
t%e similarity etween t%em on a scale
of 4 to B.
L5,8R "c%aracterLe3)ression$ Converts two string and eval&ates t%e
similarity etween t%em on a scale of 4
to B.
LTRI!"c%aracterLe3)ression$ Ret&rns t%e data wit% o&t leading
rac+ets
P/TI:D8;"Q^)atternR* e3)ression$ Ret&rns t%e starting )osition of t%e first
occ&rrence of t%e )attern in t%e
s)ecified e3)ression* -ero if t%e )attern
is not fo&nd.
R8PLIC/T8"c%arLe3)ression*
integerLe3)ression
Re)eats a c%aracter e3)ression a
s)ecified n&mer of times.
R8V8RS8"c%aracterLe3)ression$ Ret&rns t%e reverse of c%aracter
e3)ression.
RIC<T"c%aracterLe3)ression*
integerLe3)ression$
Ret&rns t%e )art of t%e c%aracter string
from t%e rig%t.
RTRI!"c%aracterLe3)ression$ Ret&rns t%e data wit%o&t tailing lan+s.
S5>:D8;"c%aracterLe3)ression$ Ret&rns t%e fo&r'digit code to eval&ate
t%e similarity of two c%aracter strings.
SP/C8"n&mericLe3)ression$ Ret&rns a string of re)eated s)aces.
T%e n&mer of s)aces is e(&al to t%e
integer e3)ression.
STR"float e3)ressionU*lengt%U*decimalVV$ Ret&rns c%aracter data converted from
n&meric data.
ST>99"c%aractaerLe3)ression4*start*lengt%*
c%aracterLe3)ression$
Deletes lengt% c%aracters from first
c%aracter e3s)ression at start and t%en
inserts c%aracter e3)ression6 into
c%aracter e3)ression.
>PP8R"c%aracterLe3)ression$ Converts t%e c%aracter e3)ression into
Visit: www.gcreddy.net for Testing Information
48
Visit: www.gcreddy.com for QTP Information
&))er case.
Date Functions9
T%e synta3 is:
S8L8CT dateLf&nction")arameters$
F0,"TI6, D=S"5I>TI6,
D/T8/DD"date)art* n&mer* date$ /dds t%e no.of date)arts to date.
D/T8DI99"date)art* date4* date6$ Ret&rns t%e n&mer of date)arts
etween two dates.
D/T8:/!8"date)art* date$ Ret&rns t%e integer val&e of t%e date
)art.
D/T8P/RT"date)art*date$ Ret&rns t%e integer val&e of t%e date
)art.
C8TD/T8"$ Ret&rns t%e c&rrent date and time.
83am)les:
SELECT GETDATE()
T%e aove statement dis)lays t%e c&rrent system date and time wit% t%e %el)
of t%e C8TD/T8 f&nction.
SELECT DATEDIFF(yy,ord_date,getdate())
T%is statement &ses t%e D/T8DI99 f&nction to find t%e difference etween t%e
c&rrent date and t%e orderLdate* from sales tales. T%e difference s%o&ld e
e3)ressed in terms of n&mer of years.
SELECT title, DATEPART(yy,pubdate) FROM titles.
T%e aove statement &ses t%e D/T8P/RT f&nction to ret&rn t%e year w%en t%e oo+
was )&lis%ed* along wit% t%e title name.
SELECT Title=title_id, Month=dATENAME(mm,pubdate), year=DATENAME(yy,
pubdatae) FROM titles.
Data "onversion9
SQL server %andles certain dataty)e conversion a&tomatically. If a c%aracter
e3)ression is com)ared wit% an int e3)ression* SQL server ma+es t%e conversion
a&tomatically for t%e com)arison"im)licit conversion$.
Visit: www.gcreddy.net for Testing Information
49
Visit: www.gcreddy.com for QTP Information
T%e C5:V8RT f&nction is &sed to c%ange data from one ty)e to anot%er w%en SQL
server cannot im)licitly )erform a conversion. >sing t%e C5:V8RT f&nction* data can
e modified in variety of styles.
T%e synta3 is:
4ggregate Functions
/ggregate f&nctions are &sed to )rod&ce s&mmary data &sing tales.

Function >ara-eters Descri/tion
/VC (/LL/DISTI:CTV e3)ression Ret&rns t%e average of val&es
s)ecified in t%e e3)ression* eit%er
all records or distinct records
S>! "/LL/DISTI:CTV e3)ression$ Ret&rns t%e s&m of val&es
s)ecified in t%e e3)ression* eit%er
all records or distinct records.
!I: "e3)ression$ Ret&rns t%e minim&m of a val&e
s)ecified in t%e e3)ression.
!/; "e3)ression$ Ret&rns t%e ma3im&m of a val&e
s)ecified in t%e e3)ression.
C5>:T "/LL_ DISTI:CT e3)ression$ Ret&rns t%e n&mer of &ni(&e or
all records s)ecified in an
e3)ression.
C5>:T "]$ Ret&rns t%e total n&mer of
records s)ecified in an e3)ression.
=xa-/!es of 4ggregate functions
S8L8CT Q/verage Price1T/VC")rice$
9R5! titles
Ret&rns t%e average val&e of all t%e
)rice val&es in t%e titles tale wit%
&ser'defined %eading.
S8L8CT QS&mRTS>!"DISTI:CT
advance$ 9R5! titles
Ret&rns t%e s&m val&e of all't%e &ni(&e
advance val&es in t%e titles tale wit%
&ser'defined %eading.
S8L8CT Q!inim&m 2td
SalesRT!I:"ytdLsales$ 9R5! titles
Ret&rns t%e minim&m val&e of
ytdLsales val&e in t%e titles tale wit%
&ser'defined %eading.
S8L8CT Q!a3im&m 2td
SalesRT!/;"ytdLsales$ 9R5! titles
Ret&rns t%e ma3im&m val&e of
ytdLsales in t%e titles tale wit% &ser'
defined %eading.
S8L8CT Q>ni(&e
PriceRTC5>:T"DISTI:CT )rice$ 9R5!
titles
Ret&rns t%e n&mer of &ni(&e )rice
val&es in t%e titles tale wit% &ser'
defined %eading.
S8L8CT QPriceTC5>:T")rice$ 9R5! Ret&rns t%e n&mer of total n&mer of
Visit: www.gcreddy.net for Testing Information
50
S8L8CT 2tdLSalesTC5:V8RT"c%ar"4=$*ytdLsales$
9R5! titles.
S8L8CT C5:V8RT"int* -i)$ 9R5! a&t%ors
CONVERT(datatype[(length), expression[,style])
Visit: www.gcreddy.com for QTP Information
titles )rice val&es in t%e titles wit% &ser'
defined %eading.
Se!ecting 5ows
T%ere are sit&ations in w%ic% only a few rows need to e retrieved from t%e
tale ased on a condition. T%e ,<8R8 cla&se* is )rovided y SQL server* to s)ecify
a condition.
T%e synta3 for &sing t%e ,<8R8 cla&se is:
83am)le:
Searc8 &ased 6n "onditions
SQL Server )rovides few met%ods of searc%ing rows in a tale. T%ese
met%ods can e roadly categori-ed into t%e following categories.
Com)arison o)erators li+e T* K* X* KT* XT* `T* `X and `K
Range o)erators li+e #8T,88: and :5T #8T,88:.
List o)erators line I: and :5T I:.
String o)erators li+e LIH8 and :5T LIH8.
>n+nown val&es li+e IS :>LL and :5T :>LL.
Logical o)erators li+e /:D * 5R and :5T.
"o-/arison 6/erator
T%e command synta3 is:
S8L8CT col&mnLlist 9R5! taleLname ,<8R8 e3)ression4
com)arisonLo)erator e3)ression6
*a!id "o-/arison o/erators
6/erator Descri/tion
K =Fua! to
A Greater t8an
L Less t8an
AK Greater t8an or =Fua! to
LK Less t8an or =Fua! to
LAE MK ,ot =Fua! to
MA ,ot Greater t8an
ML ,ot Less t8an
() "ontro!s >recedence
=xa-/!es9
Visit: www.gcreddy.net for Testing Information
51
SELECT column_list FROM table_name WHERE search_condition
SELECT * FROM publishers WHERE state = MA
SELECT title FROM titles WHERE type=business
SELECT stor_id, ord_num, title_id FROM sales WHERE qty>20
SELECT type, title_id, price FROM titles WHERE price * ytd_sales<advance.
Visit: www.gcreddy.com for QTP Information
5ange 6/erator
T%e range o)erator is &sed to retrieve data t%at can e e3tracted in ranges.
T%e range o)erations are:
#8T,88:
:5T #8T,88:
T%e synta3 is:
List 6/erator
T%e synta3 is:
String 6/erator
SQL Server )rovides a )attern'matc%ing met%od for string e3)ressions &sing
t%e LIH8 +eyword wit% t%e wildcard c%aracters. T%e LIH8 +eyword is &sed to select
t%ose rows t%at matc% t%e s)ecified )ortion of c%aracter string. T%e LIH8 +eyword
allows wildcard c%aracters t%at can e &sed as a )art of an e3)ression.
?i!d card Descri/tion
^ Re)resents any string of -ero or more c%aracters"s$
Visit: www.gcreddy.net for Testing Information
52
S8L8CT col&mnLlist 9R5! taleLname ,<8R8 e3)ression4 rangeLo)erator
e3)ression6 /:D e3)ression6
=xa-/!es9
4. S8L8CT title from titles ,<8R8 advance #8T,88: 6=== /:D E===
6. S8L8CT title 9R5! titles
,<8R8 advance :5T #8T,88: B=== /:D E===
SELECT column_list FROM table_name WHERE expression
list_operator(value_list)
Examples:
1. SELECT pub_name, city, state FROM publishers
WHERE state IN (MA, DC)
2. SELECT pub_name, city, state FROM publishers
WHERE state NOT IN (MA, DC)
Visit: www.gcreddy.com for QTP Information
' Re)resents a single c%aracter
UV Re)resents any single c%aracter wit%in t%e s)ecified range.
UaV Re)resents any single c%aracter not wit%in t%e s)ecified
range.
83am)les of t%e LIH8 o)erator wit% wildcards.
=xa-/!e Descri/tion
S8L8CT title 9R5! titles ,<8R8
ty)e LIH8 Q&s^R
Ret&rns all titles from titles tale w%ere first
t%ree c%aracters of t%e col&mn ty)e are Q&sR
S8L8CT ] 9R5! )&lis%ers
,<8R8 co&ntry LIH8 Q>SLR
Ret&rns all rows from )&lis%ers tale w%ere
co&ntry name is t%ree c%aracters long and
starts wit% >S w%ere t%e t%ird c%aracter can
e anyt%ing.
S8L8CT titleLid* )rice 9R5! titles
,<8R8 titleLid LIH8 QPUSCVV^R
Ret&rns all col&mns from t%e titles tale
w%ere titleLid starts wit% t%e c%aracter P and
contains S or C in t%e second )osition
followed y any n&mer of c%aracters.
S8L8CT titleLid* )rice 9R5! titles
,<8R8 titleLid* LIH8 QPUaCV^R
Ret&rns all titleLid and )rice from t%e titles
tale w%ere titleLid starts wit% P and does
not contain and S as t%e second c%aracter
and t%e t%ird )osition onwards can contain
any c%aracters.
0n2nown *a!ues
>n+nown val&es refer to t%e data entered in t%e form of t%e :>LL +eyword.
In SQL serve terms* :>LL is an &n+nown val&e or t%e val&e for w%ic% data is not
availale. T%e rows containing t%e :>LL val&es can e retrieved y &sing t%e IS :>LL
+eyword in t%e ,<8R8 cla&se.
T%e Synta3 is:
S8L8CT col&mnLlist 9R5! taleLname
,<8R8 col&mnLname &n+nownLval&eLo)erator.
S8L8CT title* ytdLsales 9R5! titles ,<8R8 ytdLsales IS :>LL
Logica! 6/erator
65 < Ret&rns t%e res&lt w%en any of t%e s)ecified searc% conditions is
tr&e.
4,D < ret&rns t%e res&lt w%en all of t%e s)ecified searc% conditions
are tr&e.
,6T < &negates t8e ex/ression t8at fo!!ows itG
S8L8CT col&mnLlist 9R5! taleLname
,<8R8 conditionalLe3)ressionb/:Dc5RdU:5TV conditionalLe3)ression.
=xa-/!es of Logica! o/erators
=xa-/!e Descri/tion
S8L8CT ] 9R5! )&lis%ers ,<8R8
cityTR#ostonR 5R cityTRParisR
Ret&rns all t%e rows s)ecific to t%e
conditions* even if any one of t%e
conditions is tr&e.
Visit: www.gcreddy.net for Testing Information
53
Visit: www.gcreddy.com for QTP Information
S8L8CT )&lis%ers ,<8R8
cityTR#ostonR /:D cityTR!/R
Ret&rns all t%e rows s)ecific to t%e
conditions* w%en ot% t%e conditions
are tr&e.
S8L8CT ] 9R5! )&lis%ers ,<8R8
cityTR#ostonR 5R :5T cityTRParisR
Ret&rns all t%e rows s)ecific to t%e
conditions* e3ce)t t%e rows s)ecified
wit% t%e condition after :5T o)erator.
Distinct
T%e distinct cla&se removes d&)licate rows from t%e res&lt set. D&)licate rows
can e eliminated y &sing t%e DISTI:CT +eyword in t%e S8L8CT statement.
Syntax9
T6> and >=5"=,T
T%e T5P cla&se limits t%e n&mer of rows ret&rned in t%e res&lt set.
T%e synta3 is:
TOP n [PERCENT]
,%ere n s)ecifies t%e n&mer of rows are to e ret&rned* if P8RC8:T is not
s)ecified. If P8RC8:T is s)ecified* n s)ecifies t%e )ercentage of t%e rows to e
ret&rned.
T%e T5P cla&se is &sed wit% t%e S8L8CT statement.
T%e following e3am)le ret&rns t%e to) 6= rows of t%e res&lt set.
SELECT TOP 20
T%e ne3t e3am)le ret&rns t%e 4=^ of rows from to) of t%e res&lt set.
SELECT TOP 10 PERCENT
It t%e S8L8CT statement* incl&ding T5P* %as and 5RD8R #2 cla&se* t%en t%e rows
to e ret&rned are selected after t%e 5RD8R #2 statement %as een a))lied.
Visit: www.gcreddy.net for Testing Information
54
SELECT [ALL|DISTINCT] column_name
FROM table_name
WHERE search_condition
Example:
SELECT DISTINCT title_id
FROM titleauthor
WHERE title_id LIKEPS%
Visit: www.gcreddy.com for QTP Information
SUB QUERIES
/ s& (&ery can e defined as a gro&) of nested S8L8CT statements inside a
S8L8CT* I:S8RT* >PD/T8 or D8L8T8 statement. S& (&ery can also e &sed inside
t%e ,<8R8 or </VI:C cla&ses of t%e o&ter S8L8CT* I:S8RT* >PD/T8 or D8L8T8
statements. S8L8CT statements containing one or more s& (&eries are called
nested (&eries.
T%e command synta3 is:
/ s&(&ery m&st e enclosed wit%in )arent%eses and cannot &se 5RD8R #2*
C5!P>T8 #2 or 95R #R5,S8 cla&ses. SQL Server does not im)lement any
restriction on level of nesting w%ile &sing s&(&eries* SQL Server im)oses
restrictions on t%e n&mer of tales or views &sed in a s&(&ery or a .oin.
SQL Server eval&ates t%e inner (&ery first and ret&rns t%e res&lt to t%e o&ter (&ery
for t%e final res&lt set.
T%e o&ter (&ery always de)ends on t%e eval&ation res&lt of t%e s&(&ery.
S&(&eries can e divided into t%ree catefories de)ending &)on t%e val&es t%ey
ret&rnG
S& (&eries t%at o)erate on lists: t%is ty)e of (&ery ret&rns single'col&mn'
m&lti)le val&es res&lts and are im)lemented &sing t%e I: cla&se. T%e synta3
is as follows:
S&(&eries t%at are introd&ced wit% an &nmodified com)arison o'erator: t%is
ty)e of (&ery ret&rns single col&mn'single val&e res&lts for o&ter (&ery
eval&ation and is im)lemented &sing &nmodified com)arison
Visit: www.gcreddy.net for Testing Information
55
(SELECT [ALL|DISTINCT] suquery_select_list
[FROM {table_nmae | view_name}
[[,table_name2|view_name2}]
[..,{table_name16|view_name16{]]
[WHERE clause]
GROUP BY clause]
[HAVING clause])
WHERE expression [NOT] IN (subquery)
Visit: www.gcreddy.com for QTP Information
o)erators"o)erators wit%o&t t%e /:2 or /LL +eywords$ t%e synta3 is as
follows:
S&(&eries t%at c%ec+ for t%e e3istence of data: t%is ty)e of (&ery c%ec+s for
t%e e3istence of records in a tale t%at are &sed in t%e inner (&ery* and
ret&rns eit%er a TR>8 or a 9/LS8 V/L>8 ased on t%e e3istence of data. T%is
is im)lemented &sing t%e 8;ISTS +eyword. T%e synta3 is as follows:c
SuQueries ?it8 I,
/ s&(&ery introd&ced wit% I: ret&rns -ero or more val&es. Consider t%e
following e3am)le w%ere all a&t%or IDRS* from t%e TITL8/>T<5R tale* are dis)layed
w%ose oo+s are sold:
SQL Server returns a list of all title IDs to the main query then lists all the
authors, whose books are sold, in the result set.
Consider t%e following e3am)le w%ere t%e server ret&rns a list of )&lis%er IDs to t%e
main (&ery* and t%en determines w%et%er eac% )&lis%erRs )&Lid is in t%at list:
T%e inner (&ery is eval&ated first and t%en t%e res&lt set is sent to t%e o&ter (&ery.
Consider anot%er s&(&ery wit% t%e I: cla&se:
T%e inner (&ery is eval&ated first and t%en t%e res&lt set is sent to t%e o&ter (&ery.
T%e :5T I: cla&se is &sed in t%e same way as t%e I: cla&se. Consider t%e following
e3am)le.
Visit: www.gcreddy.net for Testing Information
56
,<8R8 e3)ression com)arisonLo)erator U/:2_/LLV "s&(&ery$
WHERE [NOT] EXISTS (subquery)
SELECT au_id
FROM titleauthor
WHERE title_id IN (SELECT title_id FROM sales)
S8L8CT )&lis%erT)&Lname
9R5! )&lis%ers
,<8R8 )&Lid I: " S8L8CT )&Lid 9R5! titles ,<8R8 ty)eTR&sinessR$
S8L8CT ty)eTty)e* /verageT/VC"ytdLsales$
9R5! titles
,<8R8 ty)e I: "S8L8CT ty)e 9R5! titles
,<8R8 titleT1 t%e &sy e3ec&tiveRs dataase g&ide1 or titleTRIs /nger t%e 8nemyZR$
CR5>>P #2 ty)e
Visit: www.gcreddy.com for QTP Information
Su Queries wit8 =JISTS
T%e s&(&ery* w%en &sed wit% t%e 8;ISTS cla&se* always ret&rns data in
terms of TR>8 5R 9/LS8 and )asses t%e stat&s to t%e o&ter (&ery to )rod&ce t%e
res&lts set. T%e s&(&ery ret&rns a TR>8 val&e if t%e res&lt set contains any rows.
T%e (&ery introd&ced wit% t%e 8;ISTS +eyword differs from ot%er (&eries. T%e
8;ISTS +eyword is not )receded y any col&mn name* constant or t%ere e3)ression
and it contains an asteris+ "]$ in t%e S8L8CT list.
/ggregate f&nctions can also e &sed in s&(&eries. Consider t%e following e3am)le
w%ic% dis)lays t%e titles of all t%ose oo+s for w%ic% t%e advance is more t%an t%e
average advance of &siness related oo+s.
SuFuery 5estrictions9
T%e restrictions im)osed are:
T%e col&mn list of t%e select statement of a s&(&ery introd&ced wit% t%e
com)arison o)erator can incl&de only one col&mn.
T%e col&mn &sed in t%e ,<8R8 cla&se of t%e o&ter (&ery s%o&ld e
com)atile wit% t%e col&mn &sed in t%e select list of t%e inner (&ery.
T%e DISTI:CT +eyword cannot e &sed wit% t%e s&(&eries t%at incl&de t%e
CR5>P #2 cla&se.
Visit: www.gcreddy.net for Testing Information
57
SELECT pub_id, pub_name
FROM publishers
WHERE pub_id NOT IN (SELECT pub_id FROM titles
WHERE type=mod_cook)
1. SELECT pub_name
FROM publishers
WHERE EXISTS (SELECT * FROM titles WHERE type=business)
2. SELECT pub_name
FROM publishers
WHERE EXISTS (SELECT * FROM publishers WHERE City=Paris)
SELECT Title=title
FROM titles
WHERE advance>(SELECT AVG (advance) from titles
WHERE type=business)
Visit: www.gcreddy.com for QTP Information
T%e 5RD8R #2 cla&se* CR5>P #2 cla&se and I:T5 +eyword cannot e &sed in
a s&(&ery* eca&se a s&(&ery cannot mani)&late its res&lt internally.
Do not s)ecify more t%an one col&mn name in t%e s&(&ery introd&ced wit%
t%e 8;ISTS +eyword.
/ view created wit% a s&(&ery cannot e &)dated.
,ested Su Queries9
/ s& (&ery can contain one or more s&(&eries. T%ere is no restriction in t%e
n&mer of s&(&eries t%at yo& can incl&de wit% S8L8CT* I:S8RRT* >PD/T8 or
D8L8T8 statements.
=xa-/!e9
=xa-/!e Descri/tion
S8L8CT titleLidTtitleLid* TitleTtitle
9R5! title
,<8R8 )rieK/LL"S8L8CT )rice
9R5! titles
,<8R8 )&LidTR=IAJR$
Lists all t%e titles along wit% t%eir IDs
from t%e titles tale w%ere )rice is
greater t%an t%e ma3im&m )rice of oo+s
)&lis%ed y t%e )&lis%er wit% )&lis%er
ID =IAJ.
S8L8CT titleLID T titleLid* Title T title
9R5! titles
,<8R8 )rice K/:2 "S8L8CT )rice
9R5! titles
,<8R8 )&Lid T e=IAJe$
Lists all t%e titles along wit% t%eir titles
IDs from t%e titles tale w%ere )rice is
greater t%an t%e minim&m )rice of oo+s
)&lis%ed y t%e )&lis%er wit% )&lis%er
ID =IAJ.
S8L8CT )&lis%erLID T )&Lid* :ame T
)&Lname
9R5! )&lis%ers
,<8R8 city T /:2 "S8L8CT city 9R5!
a&t%ors$
Lists all t%e )&lis%ers w%ere city is sane
as of any a&t%or.
S=L="T I,T6 State-ent
/ S8L8CT statement wit% an I:T5 cla&se is &sed to store t%e res&lt set in a new
tale wit%o&t a data definition )rocess. T%e S8L8CT I:T5 statement creates a new
tale* if t%e tale already e3ists t%en t%e o)eration fails.
Visit: www.gcreddy.net for Testing Information
58
1. SELECT Author Name=SUBSTRING (au_fname, 1,1)+.+au_lastname
FROM authors WHERE au_id IN(SELECT au_id FROM titleauthor
WHERE title=Net Etiquette))
2. SELECT Author ID=au_id, Name=SUBSTRING (au_fnmae, 1,1) +
.+au_lname FROM authors WHERE au_id IN (SELECT au_id FROM titleauthor
WHERE type=business))
Visit: www.gcreddy.com for QTP Information
T%e synta3 of t%e S8L8CT I:T5 statement is:
T%e S8L8CT I:T5 cla&se creates a )ermanent tale if t%e select into/&l+ co)y
dataase o)tion is set. If t%e select into/&l+co)y dataase o)tion is not set* t%en
only local tem)orary tales ")refi3ed y N$* and gloal tem)orary tales ")refi3ed y
NN$ can e created.
T%e select into/&l+co)y dataase o)tion can e set &sing t%e following command:

S8L8CT titleLid* title
I:T5 newtitles
9rom titles
,<8R8 )rice KO4E
Col&mn names in t%e new tale can e c%anged w%ile s)ecifying t%e col&mns in t%e
S8L8CT statement. Consider t%e following e3am)le wit% t%e new col&mn names:
0,I6,
SQL Server )rovides a &ni(&e o)erator +nown as t%e >:I5: o)erator t%at is &sed
to comine t%e res&lt set or more (&eries.
T%e synta3 is:


Visit: www.gcreddy.net for Testing Information
59
SELECT columns_list
INTO new_table_name
FROM table_names
WHERE conditions
sp_dboption pubs, select into / bulkcopy , true
SELECT Title _ID = title _id, Title_Name =title
INTO new titles 1
FROM titles
WHERE advance >$7000
SELECT column_list [INTO new_table_name]
[FROM clause]
[WHERE clause]
[GROUP BY clause]
[HAVING clause].]
[ORDER BY clause]
[COMPUTE clause]
Visit: www.gcreddy.com for QTP Information
#y defa&lt* t%e res&lt set of t%e >:I5: o)erator removes t%e d&)licate rows from t%e
(&eries comined* &ntil an /LL cla&se is s)ecified wit% t%e >:I5: o)erator.
T%e (&eries comined wit% t%e >:I5: o)erator m&st contain an e(&al n&mer of
col&mns or e3)ressions* and t%ey m&st e com)atile wit% eac% ot%er
T%ere are two tales: regionLeast and regionLwest. T%e regionLeast tale contains
t%e em)loyee id* name and address of t%e em)loyees of t%e eastern region. T%e
regionLwest tale contains t%e em)loyee id* name and t%e address of t%e em)loyees
of t%e western region.
T%e regionHeast tale contains t%e following data:
em)Lid em)Lname em)Ladd
* ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '' '' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
8==4 Ceorge A6A* Par+ /ven&e Street
8==6 Wac+ BIE* #arara Lines
8==A :ancy JF* #an+ Street
T%e regionHwest tale contains t%e following data:
8m)Lid em)Lname em)Ladd
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '' ' ' ' ' ' ' ' ' ' ' ' ' '' ' ' ' ' ' ' ' '
,==4 !aria BE* Canara Street
,==6 Wames 46* #l&e Lines
,==A Will DF* Civil Lines
T%e following statement dis)lays em)loyee ids and names of t%e ot% t%e regions:
east and t%e west.
SELECT emp_id emp_name FROM region_east
Union
SELECT emp_id, emp_name FROM region_west
SELECT Employee ID =emp_id, Employee Name=emp_name FROM region_east
Union
SELECT emp_, emp_name FROM region_west
5u!es 5egarding t8e use of t8e 0,I6, 6/erator
T%e restrictions im)osed y SQL Server on t%e &se of t%e >:I5:
o)erator are listed elow:
Visit: www.gcreddy.net for Testing Information
60
Visit: www.gcreddy.com for QTP Information
Corres)onding col&mns in t%e individ&al (&eries of a >:I5: statement m&st
occ&r in t%e same order* eca&se >:I5: com)ares t%e col&mns in t%e order
s)ecified in t%e individ&al (&eries.
T%e col&mns or e3)ressions &sed in one (&ery m&st e e(&al in n&mer* and
s%o&ld e com)atile wit% t%e col&mns or e3)ressions of ot%er (&eries.
T%e first (&ery in t%e >:I5: statement can only contain t%e I:T5 cla&se to
store t%e final res&lt set. T%e I:T5 cla&se cannot e &sed wit% any (&ery
ot%er t%an t%e first (&ery w%ile im)lementing t%e >:I5: o)erator.
T%e 5RD8R #2 and C5!P>T8 #2 cla&ses cannot e &sed in an individ&al
(&ery. T%ese cla&ses can e &sed only at t%e end of t%e last (&ery to
s&mmari-e and order t%e final res&lt set.
T%e CR5>P #2 and </VI:C cla&ses can only e &sed wit% individ&al (&eries
and cannot e &sed for t%e final res&lt to e set.
T%e >:I5: o)erator can also e &sed wit% t%e I:S8RT statement.
*I=?S
/ view is a virt&al tale* w%ic% gives access to a s&set of col&mns from one or more
tales. <ence* a view is an o.ect t%at derives its data from one or more tales.
T%ese tales are referred to as t%e ase tales or t%e &nderlying tales.
Views ens&re sec&rity of data y restricting access to t%e following data:
S)ecific rows of t%e tale
S)ecific col&mns of t%e tale.
Rows fetc%ed y &sing .oins.
Statistical s&mmary of data in a given tale.
S&sets of anot%er view or a s&set of views and tales
Common e3am)les of views incl&de:
/ s&set of rows or col&mns of a ase tale.
/ &nion of two or more tales
/ .oin of two or more tales
/ statistical s&mmary of a ase tales
/ s&set of anot%er view* or some comination of views and ase
tales.
:anaging *iews
>sing t%e CR8/T8 VI8, statement we can create a view.
T%e synta3 of t%e CR8/T8 VI8, statement is:
T%e restrictions im)osed on views are as follows:
Visit: www.gcreddy.net for Testing Information
61
CREATE VIEW view_name
[(column_name [,column_name].)]
[WITH ENCRYPTION]
AS select_statement[WITH CHECK OPTION]
Visit: www.gcreddy.com for QTP Information
/ view can e created only in t%e c&rrent dataase.
/ view can e created only if t%ere is t%e S8L8CT )ermission on its ase
tale.
T%e S8L8CT I:T5 statement cannot e &sed in a view declaration statement.
/ view cannot derive its data from tem)orary tales.
=xa-/!e9
T%e aove statements create a view named c&stview* w%ic% contains t%e
c&stoemerid* com)anyname and t%e )%one col&mns of t%e c&stomer tale. T%e
following statement can e &sed to e3ec&te a view:
Getting *iew Infor-ation
SQL Server stores information in a view in t%e following system tales.
Ss!b"ects#stores t%e name of t%e view
Sysco!u-ns'stores t%e names of t%e col&mns defined in t%e view.
Ssdepends#stores information on t%e view de)endencies
Ssc!mments#stores t%e te3t of t%e view definition
4!tering a view
/ view can e modified wit%o&t dro))ing it. It ens&res t%at t%e )ermissions on
t%e view are not lost. / view can e altered wit%o&t affecting its de)endent
o.ects* s&c% as* triggers and stores )roced&res.
/ view can e modified &sing t%e /LT8R VI8, statement.
T%e synta3 of /LT8R VI8, statement is:
Visit: www.gcreddy.net for Testing Information
62
USE NORTHWIND
GO
CREATE VIEW custview
AS
SELECT customerid, companyname, phone FROM customers
GO
SELECT * from custview
ALTER VIEW view_name([column_name])
[WITH ENCRYPTION]
AS
Select_statement
[WITH CHECK OPTION]
Example:
ALTER VIEW custview
AS
SELECT customerid, companyname, phone, fax
From customers
Visit: www.gcreddy.com for QTP Information
T%e statement generates t%e res&lts:
SELECT * FROM custview
Dro//ing a *iew
/ view can e dro))ed from a dataase &sing t%e DR5P VI8, statement. ,%en
a view is dro))ed* it %as no effect on t%e &nderlying tale"s$. Dro))ing a view
removes its definition and all )ermissions assigned to it. 9&rt%er more if &sers
(&ery any views t%at refer to a dro))ed view* t%ey receive an error message.
<owever* dro))ing a tale t%at refers to a view does not dro) t%e view
a&tomatically. 2o& m&st dro) it e3)licitly.
T%e synta3 of DR5P VI8, statement is:
DROP VIEW view_name
,%ere viewLname is t%e name of t%e view to e dro))ed.
It is )ossile to dro) m&lti)le views wit% a single DR5P VI8,. / comma in t%e DR5P
statement se)arates eac% view t%at needs to e dro))ed.
5ena-ing a *iew
/ view can e renamed wit% o&t dro))ing it. T%is also ens&res t%at t%e
)ermissions on t%e view are not lost.
T%e g&idelines to e followed for renaming a view as follows.
T%e view m&st e in t%e c&rrent dataase.
T%e new name for t%e view m&st follow t%e r&les for renaming
identifiers.
5nly t%e owner of t%e view and t%e dataase in w%ic% view is created
can rename a view.
/ view can e renamed y &sing t%e s)Lrename system stored )roced&re.
T%e synta3 of s)Lrename is
Visit: www.gcreddy.net for Testing Information
63
Sp_rename old_viewname ,new_viewname
Example:
sp_rename custview,customerView
Visit: www.gcreddy.com for QTP Information
INDEXES
Indexes
Inde3es in dataases are similar to inde3es in oo+s. In a oo+* an inde3
allows yo& to find information (&ic+ly wit%o&t reading t%e entire oo+. In a dataase*
an inde3 allows t%e dataase )rogram to find data in a tale wit%o&t scanning t%e
entire tale. /n inde3 in a oo+ is a list of words wit% t%e )age n&mers t%at contain
eac% word. /n inde3 in a dataase is a list of val&es in a tale wit% t%e storage
locations of rows in t%e tale t%at contain eac% val&e. Inde3es can e created on
eit%er a single col&mn or a comination of col&mns in a tale and are im)lemented in
t%e form of #'trees. /n inde3 contains an entry wit% one or more col&mns "t%e
searc% +ey$ from eac% row in a tale. / #'tree is sorted on t%e searc% +ey* and can
e searc%ed efficiently on any leading s&set of t%e searc% +ey. 9or e3am)le* an
inde3 on col&mns 4* &* " can e searc%ed efficiently on 4* on 4* &* and 4* &* ".
!ost oo+s contain one general inde3 of words* names* )laces* and so on.
Dataases contain individ&al inde3es for selected ty)es or col&mns of data: t%is is
similar to a oo+ t%at contains one inde3 for names of )eo)le and anot%er inde3 for
)laces. ,%en yo& create a dataase and t&ne it for )erformance* yo& s%o&ld create
inde3es for t%e col&mns &sed in (&eries to find data.
In t%e /us sam)le dataase )rovided wit% !icrosoft? SQL Server@ 6===*
t%e e-/!oyee tale %as an inde3 on t%e e-/Hid col&mn. T%e following ill&stration
s%ows %ow t%e inde3 stores eac% e-/Hid val&e and )oints to t%e rows of data in t%e
tale wit% eac% val&e.
,%en SQL Server e3ec&tes a statement to find data in t%e e-/!oyee tale
ased on a s)ecified e-/Hid val&e* it recogni-es t%e inde3 for t%e e-/Hid col&mn
and &ses t%e inde3 to find t%e data. If t%e inde3 is not )resent* it )erforms a f&ll
tale scan starting at t%e eginning of t%e tale and ste))ing t%ro&g% eac% row*
searc%ing for t%e s)ecified e-/Hid val&e.
Visit: www.gcreddy.net for Testing Information
64
Visit: www.gcreddy.com for QTP Information
SQL Server a&tomatically creates inde3es for certain ty)es of constraints "for
e3am)le* PRI!/R2 H82 and >:IQ>8 constraints$. 2o& can f&rt%er c&stomi-e t%e
tale definitions y creating inde3es t%at are inde)endent of constraints.
T%e )erformance enefits of inde3es* %owever* do come wit% a cost. Tales
wit% inde3es re(&ire more storage s)ace in t%e dataase. /lso* commands t%at
insert* &)date* or delete data can ta+e longer and re(&ire more )rocessing time to
maintain t%e inde3es. ,%en yo& design and create inde3es* yo& s%o&ld ens&re t%at
t%e )erformance enefits o&tweig% t%e e3tra cost in storage s)ace and )rocessing
reso&rces.
Ta!e Indexes
!icrosoft? SQL Server@ 6=== s&))orts inde3es defined on any col&mn in a tale*
incl&ding com)&ted col&mns.
If a tale is created wit% no inde3es* t%e data rows are not stored in any )artic&lar
order. T%is str&ct&re is called a %ea).
T%e two ty)es of SQL Server inde3es are:
"!ustered
Cl&stered inde3es sort and store t%e data rows in t%e tale ased on t%eir +ey
val&es. #eca&se t%e data rows are stored in sorted order on t%e cl&stered
inde3 +ey* cl&stered inde3es are efficient for finding rows. T%ere can only e
one cl&stered inde3 )er tale* eca&se t%e data rows t%emselves can only e
sorted in one order. T%e data rows t%emselves form t%e lowest level of t%e
cl&stered inde3.
T%e only time t%e data rows in a tale are stored in sorted order is w%en t%e
tale contains a cl&stered inde3. If a tale %as no cl&stered inde3* its data
rows are stored in a %ea).
,onc!ustered
:oncl&stered inde3es %ave a str&ct&re com)letely se)arate from t%e data
rows. T%e lowest rows of a noncl&stered inde3 contain t%e noncl&stered inde3
+ey val&es and eac% +ey val&e entry %as )ointers to t%e data rows containing
t%e +ey val&e. T%e data rows are not stored in order ased on t%e
noncl&stered +ey.
T%e )ointer from an inde3 row in a noncl&stered inde3 to a data row is called
a row locator. T%e str&ct&re of t%e row locator de)ends on w%et%er t%e data
)ages are stored in a %ea) or are cl&stered. 9or a %ea)* a row locator is a
)ointer to t%e row. 9or a tale wit% a cl&stered inde3* t%e row locator is t%e
cl&stered inde3 +ey.
T%e only time t%e rows in a tale are stored in any s)ecific se(&ence is w%en a
cl&stered inde3 is created on t%e tale. T%e rows are t%en stored in se(&ence on t%e
cl&stered inde3 +ey. If a tale only %as noncl&stered inde3es* its data rows are stored
in a &nordered %ea).
Visit: www.gcreddy.net for Testing Information
65
Visit: www.gcreddy.com for QTP Information
Inde3es can e &ni(&e* w%ic% means no two rows can %ave t%e same val&e for t%e
inde3 +ey. 5t%erwise* t%e inde3 is not &ni(&e and m&lti)le rows can s%are t%e same
+ey val&e.
T%ere are two ways to define inde3es in SQL Server. T%e CR8/T8 I:D8;
statement creates and names an inde3. T%e CR8/T8 T/#L8 statement s&))orts t%e
following constraints t%at create inde3es:
PRI!/R2 H82 creates a &ni(&e inde3 to enforce t%e )rimary +ey.
>:IQ>8 creates a &ni(&e inde3.
CL>ST8R8D creates a cl&stered inde3.
:5:CL>ST8R8D creates a noncl&stered inde3.
T%is e3am)le s%ows t%e Transact'SQL synta3 for creating inde3es on a tale.
Visit: www.gcreddy.net for Testing Information
66
USE pubs
GO
CREATE TABLE emp_sample
(emp_id int PRIMARY KEY,
emp_name char(50),
emp_address char(50),
emp_title char(25) UNIQUE )
GO
CREATE NONCLUSTERED INDEX sample_nonclust ON emp_sample(emp_name)
GO
Visit: www.gcreddy.com for QTP Information
NORMALIZATION
,or-a!i.ation is a tec%ni(&e for )rod&cing a set of relations wit% desirale
)ro)erties* given t%e data re(&irements of an enter)rise.
T8e /rocess of nor-a!i.ation is a for-a! -et8od t8at identifies re!ations
ased on t8eir /ri-ary or candidate 7 foreign 2eys and t8e functiona!
de/endencies a-ong t8eir attriutesG
T%e Process of :ormali-ation
f:ormali-ation is often e3ec&ted as a series of ste)s. 8ac% ste) corres)onds to a
s)ecific normal form t%at %as +nown )ro)erties.
f/s normali-ation )roceeds* t%e relations ecome )rogressively more restricted in
format* and also less v&lnerale to &)date anomalies.
f9or t%e relational data model* it is im)ortant to recogni-e t%at it is only first normal
form "4:9$ t%at is critical in creating relations. /ll t%e s&se(&ent normal forms are
o)tional.
0nnor-a!i.ed for- (0,F)
/ tale t%at contains one or more re)eating gro&)s
"!inet5enta!
Visit: www.gcreddy.net for Testing Information
67
Visit: www.gcreddy.com for QTP Information
Client:o c:ame )ro)erty
:o
)/ddress rentStart rent9inis% rent owner:o o:ame
CRIJ Wo%n
+ay
PCB
PC4J
J lawrence
St*Clasgow
E :ovar Dr*
Clasgow
4'W&l'==
4'Se)'
=6
A4'/&g'
=4
4'Se)'=6
AE=
BE=
C5B=
C5DA
Tina
!&r)%y
Tony
S%aw
CREJ /line
Stewart
PCB
PCAJ
PC4J
J lawrence
St*Clasgow
6 !anor Rd*
Clasgow
E :ovar Dr*
Clasgow
4'Se)'
DD
4='5ct'
==
4':ov'
=6
4='W&n'
==
4'Dec'=4
4'/&g'=A
AE=
AI=
BE=
C5B=
C5DA
C5DA
Tina
!&r)%y
Tony
S%aw
Tony
S%aw
5e/eating grou/ K (/ro/erty,oE /4ddressE rentStartE rentFinis8E rentE owner,oE
o,a-e)
Definition of 1,F
First ,or-a! For- is a relation in w%ic% t%e intersection of eac% row and col&mn
contains one and only one val&e.
T%ere are two a))roac%es to removing re)eating gro&)s from &nnormali-ed tales:
4.Removes t%e re)eating gro&)s y entering a))ro)riate data in t%e em)ty col&mns
of rows containing t%e re)eating data.
6. Removes t%e re)eating gro&) y )lacing t%e re)eating data* along wit% a co)y
of t%e original +ey attri&te"s$* in a se)arate relation. / )rimary +ey is identified for
t%e new relation
1,F "!ient5enta! re!ation wit8 t8e first a//roac8
,it% t%e first a))roac%* we remove t%e re)eating gro&) ")ro)erty rented details$ y
entering t%e a))ro)riate client data into eac% row.
T%e ClientRental relation is defined as follows:
"!ient5enta! ( c!ient,oE /ro/erty,oE c,a-eE /4ddressE rentStartE rentFinis8E
rentE owner,oE o,a-e)
"!ient5enta!9
Visit: www.gcreddy.net for Testing Information
68
Visit: www.gcreddy.com for QTP Information
Client:o )ro)erty
:o
c:ame )/ddress rentStart rent9inis% rent owner:o o:ame
CRIJ PCB Wo%n
Hay
J lawrence
St*Clasgow
4'W&l'== A4'/&g'
=4
AE= C5B= Tina
!&r)%y
CRIJ PC4J Wo%n
Hay
E :ovar
Dr*
Clasgow
4'Se)'
=6
4'Se)'=6 BE= C5DA Tony
S%aw
CREJ PCB /line
Stewart
J lawrence
St*Clasgow
4'Se)'
DD
4='W&n'
==
AE= C5B= Tina
!&r)%y
CREJ PCAJ /line
Stewart
6 !anor
Rd*
Clasgow
4='5ct'
==
4'Dec'=4 AI= C5DA Tony
S%aw
CREJ PC4J /line
Stewart
E :ovar
Dr*
Clasgow
4':ov'
=6
4'/&g'=A BE= C5DA Tony
S%aw
1,F "!ient5enta! re!ation wit8 t8e second a//roac8
,it% t%e second a))roac%* we remove t%e re)eating gro&) ")ro)erty rented details$
y )lacing t%e re)eating data along wit% a co)y of t%e original +ey attri&te
"client:o$ in a se)arte relation.
"!ient "client:o* c:ame$
>ro/erty5enta!6wner "client:o* )ro)erty:o* )/ddress* rentStart*rent9inis%* rent*
owner:o* o:ame$
"!ient9
"!ient,o "na-e
CRIJ Wo%n Hay
CREJ /line Stewart
>ro/erty5enta!6wner9
Client:o )ro)erty
:o
)/ddress rentStart rent9inis% rent owner
:o
o:ame
CRIJ PCB J lawrence
St*Clasgow
4'W&l'== A4'/&g'=4 AE= C5B= Tina
!&r)%y
Visit: www.gcreddy.net for Testing Information
69
Visit: www.gcreddy.com for QTP Information
CRIJ PC4J E :ovar Dr*
Clasgow
4'Se)'=6 4'Se)'=6 BE= C5DA Tony
S%aw
CREJ PCB J lawrence
St*Clasgow
4'Se)'DD 4='W&n'== AE= C5B= Tina
!&r)%y
CREJ PCAJ 6 !anor
Rd*
Clasgow
4='5ct'
==
4'Dec'=4 AI= C5DA Tony
S%aw
CREJ PC4J E :ovar Dr*
Clasgow
4':ov'=6 4'/&g'=A BE= C5DA Tony
S%aw
Second ,or-a! For- (2,F)
Second normal form "6:9$ is a relation t%at is in first normal form and every non'
)rimary'+ey attri&te is f&lly f&nctionally de)endent on t%e )rimary +ey.
T%e normali-ation of 4:9 relations to 6:9 involves t%e removal of )artial
de)endencies. If a )artial de)endency e3ists* we remove t%e f&nction de)endent
attri&tes from t%e relation y )lacing t%em in a new relation along wit% a co)y of
t%eir determinant.
T%e ClientRental relation %as t%e following f&nctional de)endencies:
fd4 client:o* )ro)erty:o g rentStart* rent9inis% "Primary Hey$
fd6 client:o g c:ame "Partial de)endency$
fdA )ro)erty:o g )/ddress* rent* owner:o* o:ame "Partial de)endency$
fdB owner:o g o:ame "Transitive De)endency$
fdE client:o* rentStart g )ro)erty:o* )/ddress* rent9inis%* rent* owner:o*
o:ame "Candidate +ey$
fdJ )ro)erty:o* rentStart g client:o* c:ame* rent9inis% "Candidate +ey$
2,F "!ient5enta! re!ation
/fter removing t%e )artial de)endencies* t%e creation of t%e t%ree
new relations called Client* Rental* and Pro)erty5wner
"!ient "client:o* c:ame$
5enta! "client:o* )ro)erty:o* rentStart* rent9inis%$
Visit: www.gcreddy.net for Testing Information
70
Visit: www.gcreddy.com for QTP Information
>ro/erty6wner ")ro)erty:o* )/ddress* rent* owner:o* o:ame$
"!ient9 5enta!9
"!ient,o >ro/erty
No
renStart renFinis8
CRIJ PCB 4'W&l'== A4'/&g'=4
CRIJ PC4J 4'Se)'=6 4'Se)'=6
CREJ PCB 4'Se)'DD 4='W&n'==
CREJ PCAJ 4='5ct'== 4'Dec'=4
CREJ PC4J 4':ov'=6 4'/&g'=A
>ro/erty6wner9
/ro/erty,o /4ddress rent owner,o o,a-e
PG4 6 lawrence St,Glasgow 350 CO40 Tina Murphy
PG16 5 o!ar "r, Glasgow 450 CO#3 Tony Shaw
PG36 $ Manor %&, Glasgow 3'0 CO#3 Tony Shaw
T8ird ,or-a! For- (#,F)
/ relation t%at is in first and second normal form* and in w%ic% no non'
)rimary'+ey attri&te is transitive!y de)endent on t%e )rimary +ey.
Transitive de/endency9
/ condition w%ere /* #* and C are attri&tes of a relation s&c% t%at if / g # and # g
C* t%en C is transitively de)endent on / via # ")rovided t%at / is not f&nctionally
de)endent on # or C$.
T%e normali-ation of 6:9 relations to A:9 involves t%e removal of transitive
de)endencies y )lacing t%e attri&te"s$ in a new relation along wit% a co)y of t%e
determinant.
T%e f&nctional de)endencies for t%e Client* Rental and Pro)erty5wner relations are
as follows:
Client
fd6 client:o g c:ame "Primary Hey$
Rental
fd4 client:o* )ro)erty:o g rentStart* rent9inis% "Primary Hey$
fdE client:o* rentStart g )ro)erty:o* rent9inis% "Candidate +ey$
fdJ )ro)erty:o* rentStart g client:o* rent9inis% "Candidate +ey$
Pro)erty5wner
fdA )ro)erty:o g )/ddress* rent* owner:o* o:ame "Primary Hey$
fdB owner:o g o:ame "Transitive De)endency$
Visit: www.gcreddy.net for Testing Information
"!ient,o "na-e
CRIJ Wo%n Hay
CREJ /line Stewart
71
Visit: www.gcreddy.com for QTP Information
#,F "!ient5enta! re!ation
T%e res&lting A:9 relations %ave t%e forms:
Client "client:o* c:ame$
Rental "client:o* )ro)erty:o* rentStart* rent9inis%$
Pro)erty5wner ")ro)erty:o* )/ddress* rent* owner:o$
5wner "owner:o* o:ame$
"!ient9 5enta!9
"!ient,o >ro/erty
No
renStart renFinis8
CRIJ PCB 4'W&l'== A4'/&g'=4
CRIJ PC4J 4'Se)'=6 4'Se)'=6
CREJ PCB 4'Se)'DD 4='W&n'==
CREJ PCAJ 4='5ct'== 4'Dec'=4
CREJ PC4J 4':ov'=6 4'/&g'=A
>ro/erty6wner9 6wner9
6wner,o owner,a-e
CO40 Tina Murphy
CO#3 Tony Shaw
&oyce'"odd nor-a! for- (&",F)
/ relation is in #C:9* if and only if* every determinant is a candidate +ey.
Visit: www.gcreddy.net for Testing Information
"!ient,o "na-e
CRIJ Wo%n Hay
CREJ /line Stewart
/ro/erty
,o
/4ddress rent owner
,o
PG4 6 lawrence St,Glasgow 350 CO40
PG16 5 o!ar "r, Glasgow 450 CO#3
PG36 $ Manor %&, Glasgow 3'0 CO#3
72
Visit: www.gcreddy.com for QTP Information
T%e difference etween A:9 and #C:9 is t%at for a f&nctional de)endency / + #* A:9
allows t%is de)endency in a relation if # is a )rimary'+ey attri&te and / is not a
candidate +ey* w%ereas #C:9 insists t%at for t%is de)endency to remain in a
relation* / m&st e a candidate +ey.
=xa-/!e of &",F
fd4 client:o* interviewDate + interviewTime* staff:o* room:o "Primary Hey$
fd6 staff:o* interviewDate* interviewTime+ client:o "Candidate +ey$
fdA room:o* interviewDate* interviewTime + client:o* staff:o "Candidate +ey$
fdB staff:o* interviewDate + room:o "not a candidate +ey$
/s a conse(&ece t%e ClientInterview relation may s&ffer from &)date anmalies.
9or e3am)le* two t&)les %ave to e &)dated if t%e room:o need e c%anged for
staff:o SCE on t%e 4A'!ay'=6.
"!ient inerview
"!ient,o InterviewDate InterviewTi-e Staff,o 5oo-,o
C%'6 13(May(0$ 10)30 SG5 G101
C%'6 13(May(0$
46.== SCE C4=4
C%'4 13(May(0$
46.== SCAI C4=6
C%56
4'W&l'=6 4=.A= SCE C4=6
=xa-/!e of &",F(2)
To transform t%e ClientInterview relation to #C:9* we m&st remove t%e violating
f&nctional de)endency y creating two new relations called Interview and SatffRoom
as s%own elow*
Interview "client:o* interviewDate* interviewTime* staff:o$
StaffRoom"staff:o* interviewDate* room:o$
interview
staffroo-
Visit: www.gcreddy.net for Testing Information
73
SG5
SG3'
SG5
SG5
staffNo
10)30 1(*ul(0$ C%56
1$)00 13(May(0$ C%'4
10)30 13(May(0$ C%'6
1$)00 13(May(0$ C%'6
interviewTime interviewDate ClientNo
SG5
SG3'
SG5
staffNo
G10$ 1(*ul(0$
G10$ 13(May(0$
G101 13(May(0$
roomNo interviewDate
Visit: www.gcreddy.com for QTP Information
Fourt8 ,or-a! For- (%,F)
A relation that is in Boyce-Codd normal form and contains no nontrivial multi-
valued dependencies.
:u!ti'va!ued de/endency (:*D)
It re)resents a de)endency etween attri&tes "for e3am)le* /* # and C$ in a
relation* s&c% t%at for eac% val&e of / t%ere is a set of val&es for # and a set of val&e
for C. <owever* t%e set of val&es for # and C are inde)endent of eac% ot%er.
/ m&lti'val&ed de)endency can e f&rt%er defined as eing trivial or
nontrivial. / !VD / +K # in relation R is defined as eing trivial if
f # is a s&set of /
or
f / > # T R
/ !VD is defined as eing nontrivial if neit%er of t%e aove two conditions is
satisfied.
Fift8 ,or-a! For- (),F)
A relation that has no join dependency.
Loss!ess';oin de/endency
/ )ro)erty of decom)osition* w%ic% ens&res t%at no s)&rio&s t&)les are generated
w%en relations are re&nited t%ro&g% a nat&ral .oin o)eration.
$oin de/endency
Descries a ty)e of de)endency. 9or e3am)le* for a relation R wit% s&sets of t%e
attri&tes of R denoted as /* #* P* M* a relation R satisfies a .oin de)endency if* and
only if* every legal val&e of R is e(&al to t%e .oin of its )ro.ections on /* #* P* M.
T-SQL Programming
Visit: www.gcreddy.net for Testing Information
74
Visit: www.gcreddy.com for QTP Information
T'SQL stands for TR/:S/CT'SQL. It is a )rogramming lang&age* w%ic%
can e &sed to develo) logic on t%e dataase.
Loca! *aria!es9
/ local variale can e created y &sing t%e D8CL/R8 statement. /n initial val&e can
e assigned to t%e variale wit% t%e %el) of t%e S8L8CT statement and can e &sed
wit%in t%e trigger or )roced&re w%ere it is created or assigned t%e val&e.
T%e synta3 is:
83am)le:
Initia!i.ing *aria!es9
,e can ma+e &se of eit%er S8L8CT or S8T statements to initiali-e variales.
Syntax9
=xa-/!e9
G!oa! *aria!es9
Cloal variales are )re'defined and maintained y t%e system. T%e server to
trac+ server'wide and session's)ecific information &ses t%em. T%ey cannot e
e3)licitly set or declared. Cloal variales cannot e defined y &sers and are not
&sed to )ass information across )rocessors y a))lications. !any of t%e gloal
variales re)ort on system activity since t%e last time SQL server was startedG ot%er
re)ort information ao&t a connection.
Some common gloal variales are:
Visit: www.gcreddy.net for Testing Information
75
DECLARE @variable_name data_type [, @variable_name data_type]
DECLARE @name variable char (20)
DECLARE @age int
SELECT @varname=value (or)
SET @varname=value
SELECT @name_variable=AKINOVA KURENDIOL, @age=22
Visit: www.gcreddy.com for QTP Information
G!oa!
*aria!e
Descri/tion
SSrowco&nt Ret&rns t%e n&mer of rows )rocessed y )receding command.
SSerror Ret&rns t%e error n&mer of t%e last error generated.
SStranco&nt Ret&rns t%e transaction nesting level stat&s.
SSservername Ret&rns t%e name of t%e local SQL server.
SSversion Ret&rns t%e version of t%e SQL server &sing.
SSs)id Ret&rns t%e c&rrent )rocess ID.
SSidentity Ret&rns t%e last identity val&e &sed in an insert.
SSnestlevel Ret&rns t%e n&mer of level nested in a stored )roced&re/trigger.
SSs(lstat&s Ret&rns t%e stat&s of t%e )revio&s fetc% statement in c&rsor.
>5I,T State-ent
T%e PRI:T statement is &sed to )ass a message to t%e client )rogramRs message
%andler. It is &sed to dis)lay &ser'defined messages.
T%e synta3 is:
T%e message to e dis)layed &sing PRI:T statement can e &) to 6EE c%aracters
long.
"6,T56L'6F'FL6? L4,G04G=9
&=GI,N=,D
,%en series of statements need to e e3ec&ted it is etter to enclose t%em in loc+s.
SQL server )rovides t%e #8CI:P8:D loc+ for t%is )&r)ose and t%e statements
enclosed etween #8CI: and 8:D loc+ are +nown as statement loc+. Statement
loc+s are &sed wit% I9P8LS8 and ,<IL8 control 7of'flow lang&age. If #8CI: and
8:D are not &sed* only t%e first statement t%at immediately follows I9P8LS8 or
,<IL8 is e3ec&ted.
T%e command synta3 is:
IFN=LS= &!oc2
Visit: www.gcreddy.net for Testing Information
76
PRINT character_string|@local_variable|@@global_variable
DECLARE @myname char(20)
SELECT @myname=JOJO ALAMENTO
SELECT My Name is + @myname
PRINT @myname
GO
BEGIN
{sql_statement | statement_block}
END
Visit: www.gcreddy.com for QTP Information
Statements to e e3ec&ted conditionally are identified wit% t%e I9P8LS8 constr&ct.
T%e I9P8LS8 loc+ allows a statement or statement loc+ to e e3ec&ted w%en a
condition is TR>8 or 9/LS8.
T%e command synta3 is:
I9P8LS8 constr&cts acan e &sed in atc%es* in stored )roced&res and in ad %oc
(&eries. I9 tests can e nested* eit%er after anot%er I9 or following and 8LS8. T%ere
is no limit to t%e n&mer of nesting levels.
Consider t%e following e3am)le:
"4S= "6,ST50"T
In sit&ations w%ere yo& need a large n&mer of I9 statements* SQL Server
)rovides a C/S8 statement. T%e C/S8 statement enales m&lti)le )ossile conditions
to e managed wit%in a S8L8CT statement.
T%e synta3 is:
83am)le:
Visit: www.gcreddy.net for Testing Information
77
I9 #ooleanLe3)ression
bs(lLstaement _ statementLloc+d
U8LS8 #ooleanLe3)ression
bs(lLstatement _ statementLloc+dV
>S8 )&s
I9 "S8L8CT S>!")rice$ 9R5! titles ,<8R8 ty)eTR&sinessR$ X J==
#8CI:
PRI:T Q t%e s&m of t%e following #>SI:8SS oo+s is less t%an J=
DollarsR
PRI:T QR
9R5! titles
,<8R8 ty)eTR&sinessR
8:D
CASE
WHEN Boolean_expression THEN expression1
[[WHEN Boolean_expression THEN expression][..]
[ELSE expression]
END
Visit: www.gcreddy.com for QTP Information
?BIL= "6,ST50"T
T%e ,<IL8 constr&ct is &sef&l w%en re)eated e3ec&tion of SQL statements"s$ is
re(&ired. T%e statements are e3ec&ted re)eatedly as long as t%e s)ecified condition
is tr&e.
SQL Server )rovides #R8/H and C5:TI:>8 statements to control t%e loo)
from inside of t%e ,<IL8 constr&ct.
T%e command synta3 is:
ST65=D >56"=D05=S
Visit: www.gcreddy.net for Testing Information
78
SELECT type=
CASE type
WHEN BUSINESS THEN BUSINESS BOOK
WHEN mad_cook THEN MODERN COOKING
WHEN trad_cook THEN TRADITIONAL COOKING
WHEN psychology THEN PSYCHOLOGY BOOK
ELSE No category assigned as yet
END
Average Price=AVG(price)
Average Advance=AVG (advance)
FROM titles
WHERE title_id LIKE bu% OR title_id LIKE MC% OR title_id
LIKE PC% OR title_id LIKE PS%
GROUP BY type.
WHILE Boolean_expression
{sql_statement | statement_block}
[BREAK]
{sql_statement | statement_block}
[CONTINUE]
Example:
WHILE (SELECT AVG (price) FROM titles) < $60
BEGIN
SELECT title FROM titles
IF (SELECT MAX (price) FROM titles) > $30
BREAK
ELSE
CONTINUE
Visit: www.gcreddy.com for QTP Information
/ stored )roced&re is a gro&) of Transact'SQL statements com)iled into a single
e3ec&tion )lan.
Stored )roced&res in SQL Server are similar to )roced&res in ot%er )rogramming
lang&ages in t%at t%ey can:
/cce)t in)&t )arameters and ret&rn m&lti)le val&es in t%e form of o&t)&t
)arameters to t%e calling )roced&re or atc%.
Contain )rogramming statements t%at )erform o)erations in t%e dataase*
incl&ding calling ot%er )roced&res.
Ret&rn a stat&s val&e to a calling )roced&re or atc% to indicate s&ccess or
fail&re "and t%e reason for fail&re$.
2o& can &se t%e Transact'SQL 8;8C>T8 statement to r&n a stored )roced&re. Stored
)roced&res are different from f&nctions in t%at t%ey do not ret&rn val&es in )lace of
t%eir names and t%ey cannot e &sed directly in an e3)ression.
T%e enefits of &sing stored )roced&res in SQL Server rat%er t%an Transact'SQL
)rograms stored locally on client com)&ters are:
T%ey allow mod&lar )rogramming.
T%ey allow faster e3ec&tion.
T%ey can red&ce networ+ traffic.
T%ey can e &sed as a sec&rity mec%anism.
Stored >rocedures su//orted y SQL Server9
SQL Server s&))orts five ty)es of stored )roced&res. T%ey are:
Syste- Stored >rocedures (s/H)
!any administrative and informational activities SQL Server can e )erformed
t%ro&g% system stored )roced&res. T%ese system stored )roced&res are stored in t%e
M'ster dataase and are identified y t%e s)L)refi3. T%ey can e e3ec&ted from any
dataase.
Loca! Stored >rocedures
T%ese )roced&res will e created in t%e &ser dataase. T%e &ser w%o creates
t%e )roced&re will ecome t%e owner for t%at )roced&re.
Te-/orary Stored >rocedures
Tem)orary stored )roced&res are stored in te-/d dataase. T%ey can e
&sed in t%e case w%ere an a))lication &ilds dynamic Transact'SQL statements t%at
are e3ec&ted several times. Instead of recom)iling t%e T'SQL statements eac% time*
a tem)orary stored )roced&re can e created and com)iled on t%e first e3ec&tion*
t%en e3ec&te t%e )recom)iled )lan m&lti)le times. T%e tem)orary stored )roced&res
can e local or gloal.
Visit: www.gcreddy.net for Testing Information
79
Visit: www.gcreddy.com for QTP Information
5e-ote Stored >rocedures
T%ey are legacy feat&re of SQL Server. T%eir f&nctionality in T'SQL is limited
to e3ec&ting a stored )roced&re on a remote SQL Server installation. T%e distri&ted
(&eries in SQL Server s&))ort t%is aility along wit% t%e aility to access tales on
lin+ed 5L8D# data so&rces directly from local TLSQL statements.
=xtended Stored >rocedures
T%ese are dynamic lin+ liraries "DLLs$ t%at SQL Server can dynamically load
and e3ec&te. T%ese )roced&res r&n directly in t%e address s)ace of SQL Server and
are )rogrammed &sing t%e SQL Server 5)en Data Services /PI. T%ey are identified
y t%e 3)L)refi3.
"reating a Stored >rocedure
T%e stored )roced&res can e created &sing t%e "5=4T= >56"=D05=
statement.
Syntax9
=xa-/!e9 creating a /rocedure to insert va!ues into e-/ ta!eG
=x9 =xecuting t8e >rocedure9
T5IGG=5S
Visit: www.gcreddy.net for Testing Information
80
CREATE PROCEDURE procedure_name
[( @parameter1 data_type [OUTPUT] [, @parameter2 ..])]
AS
SQL'State-ents
Create procedure empInsert
(@eid Char,@en varchar(10),@dno int,@grd char(1),@bsal numeric(9,2),@dj datetime)
AS
Begin
INSERT INTO emp VALUES(@eid,@en,@dno,@grd,@bsal,@dj)
end
EXEC empInsert E001,sam,10,B,4500,11/3/96
Visit: www.gcreddy.com for QTP Information
/ trigger is a s)ecial ty)e of stored )roced&re t%at a&tomatically ta+es effect w%en
t%e data in a s)ecified tale is modified. Triggers are invo+ed in res)onse to an
I:S8RT* >PD/T8* or D8L8T8 statement. / trigger can (&ery ot%er tales and can
incl&de com)le3 Transact'SQL statements. T%e trigger and t%e statement t%at fires it
are treated as a single transaction* w%ic% can e rolled ac+ from wit%in t%e trigger.
If a severe error is detected "for e3am)le* ins&fficient dis+ s)ace$* t%e entire
transaction a&tomatically rolls ac+.
Triggers are &sef&l in t%ese ways:
Triggers can cascade c%anges t%ro&g% related tales in t%e dataaseG
%owever* t%ese c%anges can e e3ec&ted more efficiently &sing cascading
referential integrity constraints.
Triggers can enforce restrictions t%at are more com)le3 t%an t%ose defined
wit% C<8CH constraints.
>nli+e C<8CH constraints* triggers can reference col&mns in ot%er tales. 9or
e3am)le* a trigger can &se a S8L8CT from anot%er tale to com)are to t%e
inserted or &)dated data and to )erform additional actions* s&c% as modify
t%e data or dis)lay a &ser'defined error message.
Triggers can also eval&ate t%e state of a tale efore and after a data
modification and ta+e action"s$ ased on t%at difference.
!&lti)le triggers of t%e same ty)e "I:S8RT* >PD/T8* or D8L8T8$ on a tale
allow m&lti)le* different actions to ta+e )lace in res)onse to t%e same
modification statement.
"reating a Trigger9
2o& can &se t%e 95R cla&se to s)ecify w%en a trigger is e3ec&ted:
Visit: www.gcreddy.net for Testing Information
81
CREATE TRIGGER trigger_name
ON { table | view }
{
{ { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] }
AS
sql_statement [ ...n ]
}
}
Visit: www.gcreddy.com for QTP Information
/9T8R
T%e trigger e3ec&tes after t%e statement t%at triggered it com)letes. If t%e
statement fails wit% an error* s&c% as a constraint violation or synta3 error*
t%e trigger is not e3ec&ted. /9T8R triggers cannot e s)ecified for views* t%ey
can only e s)ecified for tales. 2o& can s)ecify m&lti)le /9T8R triggers for
eac% triggering action "I:S8RT* >PD/T8* or D8L8T8$. If yo& %ave m&lti)le
/9T8R triggers for a tale* yo& can &se s/Hsettriggerorder to define w%ic%
/9T8R trigger fires first and w%ic% fires last. /ll ot%er /9T8R triggers esides
t%e first and last fire in an &ndefined order w%ic% yo& cannot control.
/9T8R is t%e defa&lt in SQL Server 6===. 2o& co&ld not s)ecify /9T8R or
I:ST8/D 59 in SQL Server version I.= or earlier* all triggers in t%ose versions
o)erated as /9T8R triggers.
I:ST8/D 59
T%e trigger e3ec&tes in )lace of t%e triggering action. I:ST8/D 59 triggers
can e s)ecified on ot% tales and views. 2o& can define only one I:ST8/D
59 trigger for eac% triggering action "I:S8RT* >PD/T8* and D8L8T8$.
I:ST8/D 59 triggers can e &sed to )erform en%ance integrity c%ec+s on t%e
data val&es s&))lied in I:S8RT and >PD/T8 statements. I:ST8/D 59 triggers
also let yo& s)ecify actions t%at allow views* w%ic% wo&ld normally not
s&))ort &)dates* to e &)datale.
Triggers "o-/ared to "onstraints
Constraints and triggers eac% %ave enefits t%at ma+e t%em &sef&l in s)ecial
sit&ations. T%e )rimary enefit of triggers is t%at t%ey can contain com)le3
)rocessing logic t%at &ses Transact'SQL code. T%erefore* triggers can s&))ort all of
t%e f&nctionality of constraintsG %owever* triggers are not always t%e est met%od for
a given feat&re.
Entity inte$rity s%o&ld always e enforced at t%e lowest level y inde3es t%at are )art
of PRI!/R2 H82 and >:IQ>8 constraints or are created inde)endently of constraints.
Domain integrity s%o&ld e enforced t%ro&g% C<8CH constraints* and re+erenti'l
inte$rity /RI1 s%o&ld e enforced t%ro&g% 95R8IC: H82 constraints* ass&ming t%eir
feat&res meet t%e f&nctional needs of t%e a))lication.
Triggers are most &sef&l w%en t%e feat&res s&))orted y constraints cannot meet t%e
f&nctional needs of t%e a))lication. 9or e3am)le:
95R8IC: H82 constraints can validate a col&mn val&e only wit% an e3act
matc% to a val&e in anot%er col&mn* &nless t%e R898R8:C8S cla&se defines a
cascading referential action.
/ C<8CH constraint can validate a col&mn val&e only against a logical
e3)ression or anot%er col&mn in t%e same tale. If yo&r a))lication re(&ires
t%at a col&mn val&e e validated against a col&mn in anot%er tale* yo& m&st
&se a trigger.
Visit: www.gcreddy.net for Testing Information
82
Visit: www.gcreddy.com for QTP Information
Constraints can comm&nicate ao&t errors only t%ro&g% standardi-ed system
error messages. If yo&r a))lication re(&ires "or can enefit from$ c&stomi-ed
messages and more com)le3 error %andling* yo& m&st &se a trigger.
Triggers can cascade c%anges t%ro&g% related tales in t%e dataaseG %owever* t%ese
c%anges can e e3ec&ted more efficiently t%ro&g% cascading referential integrity
constraints.
Triggers can disallow or roll ac+ c%anges t%at violate referential integrity*
t%erey canceling t%e attem)ted data modification. S&c% a trigger mig%t go
into effect w%en yo& c%ange a foreign +ey and t%e new val&e does not matc%
its )rimary +ey.
If constraints e3ist on t%e trigger tale* t%ey are c%ec+ed after t%e I:ST8/D
59 trigger e3ec&tion &t )rior to t%e /9T8R trigger e3ec&tion. If t%e
constraints are violated* t%e I:ST8/D 59 trigger actions are rolled ac+ and
t%e /9T8R trigger is not e3ec&ted.
=xa-/!e9
,%ile entering t%e details of a new em)loyee* t%e salary %as to e entered
according to t%e grade. If t%e grade it c%anged* t%e asic salary s%o&ld also e
c%anged accordingly. Instead of man&ally doing t%is* t%e <R manager wanted t%e
asic salary of t%e em)loyees to e entered a&tomatically w%enever an em)loyee is
added or grade is c%anged.
So!ution9 Create salLinfo and em) tales as follows.
Insert some val&es into t%e salLinfo tale:
:ow* create t%e em) tale as follows:
:ow* create t%e re(&ired trigger as follows:
Visit: www.gcreddy.net for Testing Information
83
CREATE TABLE sal_info(grade char(1), bsal numeric(18,0))
INSERT INTO sal_info
SELECT A,1000 UNION ALL
SELECT B,2000 UNION ALL
SELECT C,3000
CR8/T8 T/#L8 em)"em)Lno int*em)Lname varc%ar"4=$*de)tLno int*grade
c%ar"4$*sal n&meric"4F*=$*do. datetime$
Visit: www.gcreddy.com for QTP Information
/n insert/"&)'te is written for t%e tale e&. ,%enever a new record is inserted or
&)dated* t%e new grade is otained from t%e inserted tale. T%e corres)onding asic
salary is otained from t%e tale s'l7in+# and t%e asic salary in t%e e& tale is set
to t%is val&e.
T%is trigger can e c%ec+ed y inserting a record wit% a n&ll val&e for t%e field 5s'l.
,%en a select statement is given* t%e val&e for sal will also e )resent.
4!tering a Trigger9
T%e definition of an e3isting trigger can e altered wit%o&t dro))ing it. T%e
altered definition re)laces t%e definition of t%e e3isting trigger wit% t%e new
definition.
Syntax
Visit: www.gcreddy.net for Testing Information
84
CREATE TRIGGER tr_emp ON emp
FOR INSERT,UPDATE
AS
DECLARE @sal numeric(18,0)
SELECT @sal=sal_info.bsal from sal_info,inserted
Where inserted.grade=sal_info.grade
UPDATE emp set bsal=@sal from emp.inserted
Where emp.emp_no=inserted.emp_no
I:S8RT I:T5 em) V/L>8S"4==*R/rvindR*A=*R#R*n&ll*getdate"$$
SELECT * FROM EMP
Emp_no emp_name dept_no gradebsal doj
100 Arvind 30 B 2000 2006-06-15
ALTER TRIGGER trigger_name
ON { table | view }
{
{ { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] }
AS
sql_statement [ ...n ]
}
}
Visit: www.gcreddy.com for QTP Information
=xa-/!e9
This example creates a trigger that prints a user-defned message to the
client when a user tries to add or change data in the emp table. Then, the
trigger is altered using ALTER TRIGGER to apply the trigger only on INSERT
activates. This trigger is helpful because it reminds the user who updates or
inserts rows into this table.
Dro//ing a Trigger9
/ trigger can e dro))ed y &sing* DR5P TRICC8R statement. / trigger gets
dro))ed a&tomatically w%en its associated tale is dro))ed. Permissions to dro) a
trigger defa&lts to t%e tale owner. #&t t%e memers of t%e system
administrators"sys')in$ and t%e dataase owner")57#;ner$ can dro) any o.ect y
s)ecifying t%e owner in t%e DR5P TRICC8R statement.
Syntax9
Disa!ing or =na!ing a Trigger9
Triggers can e enaled or disaled &sing /LT8R T/#L8 statement. 5n
disaling a trigger* t%e actions in t%e trigger are not )erformed &ntil t%e trigger is re'
enaled.
Syntax9
USER DEFINED FUNCTIONS
Visit: www.gcreddy.net for Testing Information
85
CREATE TRIGGER trig1
ON emp
WITH ENCRYPTION
FOR INSERT, UPDATE
/S R/IS8RR5R"B===F*4J*4=$
ALTER TRIGGER trig1
ON emp
FOR INSERT
/S R/IS8RR5R"B===F*4J*4=$
,RO$ TRI--.R t!"//e!#name
A0T.R TA10. ta2le#name
3.NA10. 4 ,ISA10. 5 TRI--.R
3A00 4 trigger_name6& **n7
Visit: www.gcreddy.com for QTP Information
/ >ser'Defined 9&nction is* m&c% li+e a Stored Proced&re* an ordered set of
T'SQL statements t%at are )re'o)timi-ed and com)iled and can e called to wor+ as
a single &nit. T%e )rimary difference etween t%em is %ow res&lts are ret&ned.
,it% a Stored Proced&re* yo& can )as )arameters in* and also get val&es in
)arameters )assed ac+ o&t. 2o& can ret&rn a val&e* &t t%at val&e is really intended
to indicate s&ccess or fail&re rat%er t%an ret&rn data. 2o& can also ret&rn res&lt sets*
&t yo& canRt really &se t%ose res&lt sets in a (&ery wit%o&t first inserting t%em into
some +ind of tale "&s&ally a tem)orary tale$ to wor+ wit% t%em f&rt%er.
,it% a >D9* %owever* yo& can )ass )arameters in* &t not #"t. Instead* t%e
conce)t of o&t)&t )arameters %as een re)laced wit% a m&c% more ro&st ret&rn
val&e. /s wit% system f&nctions* yo& can ret&rn a scalar val&e. /not%er advantage is
t%at t%is val&e is not limited to .&st t%e integer data ty)e as it wo&ld e for a Stored
Proced&re. Instead* yo& can ret&rn most SQL Server data ty)es.
Ty/es of 0DFOs9
T%ose t%at ret&rn a scalar val&e
T%ose t%at ret&rn a tale
Genera! Syntax for creating a 0DF9
0DFs 5eturning a Sca!ar *a!ue9
!&c% li+e SQL ServerRs own &ilt'in f&nctions* t%ey will ret&rn a scalar val&e
to t%e calling scri)t or )roced&re. 5ne of t%e tr&ly great t%ings ao&t a >D9 is t%at
yo& are not limited to an integer for a ret&rn val&e 7 instead* it can e of any valid
SQL Server data ty)e* e3ce)t for #L5#s* c&rsors* and timestam)s. 8ven if yo&
wanted to ret&rn an integer* a >D9 s%o&ld e advantage to yo& for two different
reasons:
4. >nli+e Stored Proced&res* t%e w%ole )&r)ose of t%e ret&rn val&e is to serve a
meaningf&l )iece of data 7 for Stored Proced&res* a ret&rn val&e is meant as
an indication of s&ccess or fail&re* and* in t%e event of fail&re* to )rovide
some s)ecific information ao&t t%e nat&re of t%at fail&re.
Visit: www.gcreddy.net for Testing Information
86
CREATE FUNCTION function_name
(<@parameter name> <data type>[=default value>][,n])
RETURNS {<data type>|TABLE}
AS
BEGIN
[<function statements>]
{RETURN <type as defned in RETURNS clause> |
RETURN $%SE&E'T statement()*
END
Visit: www.gcreddy.com for QTP Information
6. 2o& can )erform f&nctions in'line to yo&r (&eries "for instances* incl&de it as
)art of yo&r S8L8CT statement$ 7 yo& canRt do t%at wit% a Stored Proced&re.
"ase study9
LetRs create a tale called 5RD8RS wit% A col&mns named as 5rderID* C&stID and
5rderDate as follows
Lets insert some data into t%e tale wit% t%e &se of a sim)le T'SQL )rogram.
So* t%is gets &s 4= rows inserted* wit% eac% row eing inserted wit% todayRs date* &t
one min&te a)art from eac% ot%er.
So* now weRre ready to r&n a sim)le (&ery to see w%at orders we %ave today. ,e
mig%t try somet%ing li+e:
>nfort&nately* t%is (&ery will not get &s anyt%ing ac+ at all. T%is is eca&se
C8TD/T8"$ gets t%e c&rrent time not .&st t%e day.
T%e sol&tion is to convert t%e date to a string and ac+ in order to tr&ncate t%e time
information* t%en )erform com)arison.
Visit: www.gcreddy.net for Testing Information
87
CREATE TABLE orders(ordered int, custid int,orderdate datetime)
DECLARE @Counter int
SET @Counter =1
WHILE @Counter <= 10
BEGIN
INSERT INTO Orders
VALUES(1,1,DATEADD(mi, @Counter, GETDATE()))
SET @Counter = @Counter + 1
END
SELECT *
FROM Orders
WHERE orderdate=GETDATE()
SELECT *
FROM Orders
WHERE CONVERT(varchar(12), orderdate, 101)=CONVERT(varchar(12),
GETDATE(),101)
Visit: www.gcreddy.com for QTP Information
T%is time* we will get ac+ every row wit% todayRs date in t%e 5rderDate col&mn 7
regardless of w%at time of day t%e order was ta+en. >nfort&nately* t%is isnRt e3actly
t%e most readale code. Imagine yo& %ad a large series of dates yo& needed to
)erform s&c% com)arisons against 7 it can get very &gly indeed.
So now letRs loo+ at doing t%e same t%ing wit% a sim)le &ser'defined f&nction. 9irst*
weRll need to create t%e act&al f&nction. T%is is done wit% t%e new CR8/T8 9>:CTI5:
command* and itRs formatted m&c% li+e a Stored Proced&re. 9or e3am)le* we mig%t
code t%is f&nction li+e t%is:
,%et%er t%e date ret&rned from C8TD/T8"$ is )assed in as t%e )arameter and t%e
tas+ of converting t%e date is incl&ded in t%e f&nction ody and t%e tr&ncated date is
ret&rned.
To see t%is f&nction in action* letRs reformat o&r (&ery as follows:
,e get ac+ t%e same set as wit% t%e stand'alone (&ery. 8ven for a sim)le (&ery li+e
t%is one* t%e new code is (&ite a it more readale. T%ere is* %owever* one
re(&irement for t%is ty)e. T%e owner name is re(&ired in t%e f&nction call. SQL
Server will* for some reason* not resolve f&nctions t%e way it does wit% ot%er
o.ects.
0DFs t8at 5eturn a Ta!e9
SQL ServerRs new &ser'defined f&nctions are not limited to .&st ret&rning scalar
val&es. T%ey can ret&rn somet%ing far more interesting 7 tales.
To ma+e t%e c%ange to &sing a tale* as a ret&rn val&e is not %ard at all 7 a tale is
.&st li+e any ot%er SQL Server data ty)e as far as a >D9 is concerned. To ill&strate
t%is* weRll &ild a relatively sim)le one:
Visit: www.gcreddy.net for Testing Information
88
CREATE FUNCTION dbo.DateOnly(@dt datetime)
RETURNS varchar(12)
AS
BEGIN
RETURN CONVERT(varchar(12), @dt, 101)
END
SELECT *
FROM Orders
WHERE dbo.DateOnly(OrderDate) = dbo.DateOnly(GETDATE())
Visit: www.gcreddy.com for QTP Information
T%is f&nction ret&rns a tale of S8L8CT8ed records and does a little formatting:
.oining t%e last and first names* se)arating t%em wit% a comma* and concatenating
t%e t%ree com)onents to fill t%e address6 col&mn.
/t t%is )oint* weRre ready to &se o&r f&nction .&st as we wo&ld &se a tale 7 t%e only
e3ce)tion is t%at as was disc&ssed wit% scalar f&nctions* we m&st &se t%e two')art
naming convention:
Visit: www.gcreddy.net for Testing Information
89
USE pubs
GO
CREATE FUNCTION dbo.fnListOfAuthors()
RETURNS TABLE
AS
RETURN ( SELECT au_id,
au_lname + , + au_fname AS au_name,
address AS address1,
City + , + state + + zip AS address2
FROM authors)
GO
SELECT *
FROM dbo.fnListOfAuthors()
Visit: www.gcreddy.com for QTP Information
LOCKS
!icrosoft? SQL Server@ 6=== %as loc+ing t%at allows different ty)es of reso&rces to
e loc+ed y a transaction. To minimi-e t%e cost of loc+ing* SQL Server loc+s
reso&rces a&tomatically at a level a))ro)riate to t%e tas+. Loc+ing at a smaller
gran&larity* s&c% as rows* increases conc&rrency* &t %as a %ig%er over%ead eca&se
more loc+s m&st e %eld if many rows are loc+ed. Loc+ing at a larger gran&larity*
s&c% as tales* are e3)ensive in terms of conc&rrency eca&se loc+ing an entire tale
restricts access to any )art of t%e tale y ot%er transactions* &t %as a lower
over%ead eca&se fewer loc+s are eing maintained.
SQL Server can loc+ t%ese reso&rces "listed in order of increasing gran&larity$.
5esource Descri/tion
RID Row identifier. >sed to loc+ a single row wit%in a tale.
Hey Row loc+ wit%in an inde3. >sed to )rotect +ey ranges in
seriali-ale transactions.
Page F +iloyte 7"H#$ data )age or inde3 )age.
83tent Contig&o&s gro&) of eig%t data )ages or inde3 )ages.
Tale 8ntire tale* incl&ding all data and inde3es.
D# Dataase.
SQL Server loc+s reso&rces &sing different loc+ modes t%at determine %ow t%e
reso&rces can e accessed y conc&rrent transactions.
SQL Server &ses t%ese reso&rce loc+ modes.
Loc2 -ode Descri/tion
S%ared "S$ >sed for o)erations t%at do not c%ange or &)date data "read'only
o)erations$* s&c% as a S8L8CT statement.
>)date ">$ >sed on reso&rces t%at can e &)dated. Prevents a common form
of deadloc+ t%at occ&rs w%en m&lti)le sessions are reading*
loc+ing* and )otentially &)dating reso&rces later.
83cl&sive ";$ >sed for data'modification o)erations* s&c% as I:S8RT* >PD/T8*
or D8L8T8. 8ns&res t%at m&lti)le &)dates cannot e made to t%e
same reso&rce at t%e same time.
Intent >sed to estalis% a loc+ %ierarc%y. T%e ty)es of intent loc+s are:
intent s%ared "IS$* intent e3cl&sive "I;$* and s%ared wit% intent
e3cl&sive "SI;$.
Sc%ema >sed w%en an o)eration de)endent on t%e sc%ema of a tale is
e3ec&ting. T%e ty)es of sc%ema loc+s are: sc%ema modification
"Sc%'!$ and sc%ema staility "Sc%'S$.
Visit: www.gcreddy.net for Testing Information
90
Visit: www.gcreddy.com for QTP Information
#&l+ >)date "#>$ >sed w%en &l+'co)ying data into a tale and t%e T4&L6"I %int
is s)ecified.
Shared Locks
S%ared "S$ loc+s allow conc&rrent transactions to read "S8L8CT$ a reso&rce. :o
ot%er transactions can modify t%e data w%ile s%ared "S$ loc+s e3ist on t%e reso&rce.
S%ared "S$ loc+s on a reso&rce are released as soon as t%e data %as een read*
&nless t%e transaction isolation level is set to re)eatale read or %ig%er* or a loc+ing
%int is &sed to retain t%e s%ared "S$ loc+s for t%e d&ration of t%e transaction.
Update Locks
>)date ">$ loc+s )revent a common form of deadloc+. / ty)ical &)date )attern
consists of a transaction reading a record* ac(&iring a s%ared "S$ loc+ on t%e
reso&rce ")age or row$* and t%en modifying t%e row* w%ic% re(&ires loc+ conversion
to an e3cl&sive ";$ loc+. If two transactions ac(&ire s%ared'mode loc+s on a reso&rce
and t%en attem)t to &)date data conc&rrently* one transaction attem)ts t%e loc+
conversion to an e3cl&sive ";$ loc+. T%e s%ared'mode'to'e3cl&sive loc+ conversion
m&st wait eca&se t%e e3cl&sive loc+ for one transaction is not com)atile wit% t%e
s%ared'mode loc+ of t%e ot%er transactionG a loc+ wait occ&rs. T%e second
transaction attem)ts to ac(&ire an e3cl&sive ";$ loc+ for its &)date. #eca&se ot%
transactions are converting to e3cl&sive ";$ loc+s* and t%ey are eac% waiting for t%e
ot%er transaction to release its s%ared'mode loc+* a deadloc+ occ&rs.
To avoid t%is )otential deadloc+ )rolem* &)date ">$ loc+s are &sed. 5nly one
transaction can otain an &)date ">$ loc+ to a reso&rce at a time. If a transaction
modifies a reso&rce* t%e &)date ">$ loc+ is converted to an e3cl&sive ";$ loc+.
5t%erwise* t%e loc+ is converted to a s%ared'mode loc+.
Ecl!si"e Locks
83cl&sive ";$ loc+s )revent access to a reso&rce y conc&rrent transactions. :o ot%er
transactions can read or modify data loc+ed wit% an e3cl&sive ";$ loc+.
Intent Locks
/n intent loc+ indicates t%at SQL Server wants to ac(&ire a s%ared "S$ loc+ or
e3cl&sive ";$ loc+ on some of t%e reso&rces lower down in t%e %ierarc%y. 9or
e3am)le* a s%ared intent loc+ )laced at t%e tale level means t%at a transaction
intends on )lacing s%ared "S$ loc+s on )ages or rows wit%in t%at tale. Setting an
intent loc+ at t%e tale level )revents anot%er transaction from s&se(&ently
ac(&iring an e3cl&sive ";$ loc+ on t%e tale containing t%at )age. Intent loc+s
Visit: www.gcreddy.net for Testing Information
91
Visit: www.gcreddy.com for QTP Information
im)rove )erformance eca&se SQL Server e3amines intent loc+s only at t%e tale
level to determine if a transaction can safely ac(&ire a loc+ on t%at tale. T%is
removes t%e re(&irement to e3amine every row or )age loc+ on t%e tale to
determine if a transaction can loc+ t%e entire tale.
Intent loc+s incl&de intent s%ared "IS$* intent e3cl&sive "I;$* and s%ared wit% intent
e3cl&sive "SI;$.
Loc2 -ode Descri/tion
Intent s%ared "IS$ Indicates t%e intention of a transaction to read some "&t not
all$ reso&rces lower in t%e %ierarc%y y )lacing S loc+s on t%ose
individ&al reso&rces.
Intent e3cl&sive "I;$ Indicates t%e intention of a transaction to modify some "&t not
all$ reso&rces lower in t%e %ierarc%y y )lacing ; loc+s on t%ose
individ&al reso&rces. I; is a s&)erset of IS.
S%ared wit% intent
e3cl&sive "SI;$
Indicates t%e intention of t%e transaction to read all of t%e
reso&rces lower in t%e %ierarc%y and modify some "&t not all$
reso&rces lower in t%e %ierarc%y y )lacing I; loc+s on t%ose
individ&al reso&rces. Conc&rrent IS loc+s at t%e to)'level
reso&rce are allowed. 9or e3am)le* an SI; loc+ on a tale
)laces an SI; loc+ on t%e tale "allowing conc&rrent IS loc+s$*
and I; loc+s on t%e )ages eing modified "and ; loc+s on t%e
modified rows$. T%ere can e only one SI; loc+ )er reso&rce at
one time* )reventing &)dates to t%e reso&rce made y ot%er
transactions* alt%o&g% ot%er transactions can read reso&rces
lower in t%e %ierarc%y y otaining IS loc+s at t%e tale level.
Sche#a Locks
Sc%ema modification "Sc%'!$ loc+s are &sed w%en a tale data definition lang&age
"DDL$ o)eration "s&c% as adding a col&mn or dro))ing a tale$ is eing )erformed.
Sc%ema staility "Sc%'S$ loc+s are &sed w%en com)iling (&eries. Sc%ema staility
"Sc%'S$ loc+s do not loc+ any transactional loc+s* incl&ding e3cl&sive ";$ loc+s.
T%erefore* ot%er transactions can contin&e to r&n w%ile a (&ery is eing com)iled*
incl&ding transactions wit% e3cl&sive ";$ loc+s on a tale. <owever* DDL o)erations
cannot e )erformed on t%e tale.
B!lk Update Locks
#&l+ &)date "#>$ loc+s are &sed w%en &l+ co)ying data into a tale and eit%er t%e
T4&L6"I %int is s)ecified or t%e ta!e !oc2 on u!2 !oad tale o)tion is set &sing
s/Hta!eo/tion. #&l+ &)date "#>$ loc+s allow )rocesses to &l+ co)y data
conc&rrently into t%e same tale w%ile )reventing ot%er )rocesses t%at are not &l+
co)ying data from accessing t%e tale.
Visit: www.gcreddy.net for Testing Information
92
Visit: www.gcreddy.com for QTP Information
Dead!oc2ing
/ deadloc+ occ&rs w%en t%ere is a cyclic de)endency etween two or more t%reads
for some set of reso&rces.
Deadloc+ is a condition t%at can occ&r on any system wit% m&lti)le t%reads* not .&st
on a relational dataase management system. / t%read in a m&lti't%readed system
may ac(&ire one or more reso&rces "for e3am)le* loc+s$. If t%e reso&rce eing
ac(&ired is c&rrently owned y anot%er t%read* t%e first t%read may %ave to wait for
t%e owning t%read to release t%e target reso&rce. T%e waiting t%read is said to %ave
a de)endency on t%e owning t%read for t%at )artic&lar reso&rce.
If t%e owning t%read wants to ac(&ire anot%er reso&rce t%at is c&rrently owned y
t%e waiting t%read* t%e sit&ation ecomes a deadloc+: ot% t%reads cannot release
t%e reso&rces t%ey own &ntil t%eir transactions are committed or rolled ac+* and
t%eir transactions cannot e committed or rolled ac+ eca&se t%ey are waiting on
reso&rces t%e ot%er owns. 9or e3am)le* t%read T4 r&nning transaction 4 %as an
e3cl&sive loc+ on t%e Su//!ier tale. T%read T6 r&nning transaction 6 otains an
e3cl&sive loc+ on t%e >art tale* and t%en wants a loc+ on t%e Su//!ier tale.
Transaction 6 cannot otain t%e loc+ eca&se transaction 4 %as it. Transaction 6 is
loc+ed* waiting on transaction 4. Transaction 4 t%en wants a loc+ on t%e >art tale*
&t cannot otain it eca&se transaction 6 %as it loc+ed. T%e transactions cannot
release t%e loc+s %eld &ntil t%e transaction is committed or rolled ac+. T%e
transactions cannot commit or roll ac+ eca&se t%ey re(&ire a loc+ %eld y t%e ot%er
transaction to contin&e.
Visit: www.gcreddy.net for Testing Information
93
Visit: www.gcreddy.com for QTP Information
TRANSACTIONS
/ transaction is a se(&ence of o)erations )erformed as a single logical &nit of
wor+. / logical &nit of wor+ m&st e3%iit fo&r )ro)erties* called t%e /CID "/tomicity*
Consistency* Isolation* and D&raility$ )ro)erties* to (&alify as a transaction:
4to-icity
/ transaction m&st e an atomic &nit of wor+G eit%er all of its data modifications are
)erformed* or none of t%em is )erformed.
"onsistency
,%en com)leted* a transaction m&st leave all data in a consistent state. In a
relational dataase* all r&les m&st e a))lied to t%e transaction[s modifications to
maintain all data integrity. /ll internal data str&ct&res* s&c% as #'tree inde3es or
do&ly'lin+ed lists* m&st e correct at t%e end of t%e transaction.
Iso!ation
!odifications made y conc&rrent transactions m&st e isolated from t%e
modifications made y any ot%er conc&rrent transactions. / transaction eit%er sees
data in t%e state it was in efore anot%er conc&rrent transaction modified it* or it
sees t%e data after t%e second transaction %as com)leted* &t it does not see an
intermediate state. T%is is referred to as seriali-aility eca&se it res&lts in t%e aility
to reload t%e starting data and re)lay a series of transactions to end &) wit% t%e data
in t%e same state it was in after t%e original transactions were )erformed.
Durai!ity
/fter a transaction %as com)leted* its effects are )ermanently in )lace in t%e system.
T%e modifications )ersist even in t%e event of a system fail&re.
"ontro!!ing Transactions
/))lications control transactions mainly y s)ecifying w%en a transaction starts and
ends. T%is can e s)ecified &sing eit%er Transact'SQL statements or dataase /PI
f&nctions. T%e system m&st also e ale to correctly %andle errors t%at terminate a
transaction efore it com)letes.
Transactions are managed at t%e connection level. ,%en a transaction is started on a
connection* all Transact'SQL statements e3ec&ted on t%at connection are )art of t%e
transaction &ntil t%e transaction ends.
Visit: www.gcreddy.net for Testing Information
94
Visit: www.gcreddy.com for QTP Information
Starting Transactions
2o& can start transactions in !icrosoft? SQL Server@ as e3)licit* a&tocommit* or
im)licit transactions.
=x/!icit transactions
83)licitly start a transaction y iss&ing a BEGIN TRANSACTION statement.
4utoco--it transactions
T%is is t%e defa&lt mode for SQL Server. T%ese transactions will contain only one
statement. 8ac% individ&al Transact'SQL statement is committed w%en it com)letes.
2o& do not %ave to s)ecify any statements to control transactions.
I-/!icit transactions
Set im)licit transaction mode on t%ro&g% eit%er an /PI f&nction or t%e Transact'SQL
SET IMPLICIT7TRANSACTIONS ON statement. ,%en t%at transaction is com)leted
eit%er y &sing COMMIT / ROLLBAC-* t%e ne3t Transact'SQL statement starts a new
transaction.
=nding Transactions
2o& can end transactions wit% eit%er a C5!!IT or R5LL#/CH statement.
"6::IT
If a transaction is s&ccessf&l* commit it. / C5!!IT statement g&arantees all of t%e
transaction[s modifications are made a )ermanent )art of t%e dataase. / C5!!IT
also frees reso&rces* s&c% as loc+s* &sed y t%e transaction.
Syntax9
56LL&4"I
If an error occ&rs in a transaction* or if t%e &ser decides to cancel t%e transaction*
t%en roll t%e transaction ac+. / R5LL#/CH statement ac+s o&t all modifications
made in t%e transaction y ret&rning t%e data to t%e state it was in at t%e start of t%e
transaction. / R5LL#/CH also frees reso&rces %eld y t%e transaction.
Syntax9
Visit: www.gcreddy.net for Testing Information
95
COMMIT TRAN[SACTION] transactionName
ROLLBACK TRAN[SACTION] transactionName [savepointname]
Visit: www.gcreddy.com for QTP Information
Save/oints
Save)oints offer a mec%anism to roll ac+ )ortions of transactions. 2o& create a
save)oint &sing t%e S/V8 TR/:S/CTI5: s've&#int7n'e statement* and t%en later
e3ec&te a R5LL#/CH TR/:S/CTI5: s've&#int7n'e statement to roll ac+ to t%e
save)oint instead of rolling ac+ to t%e start of a transaction.
=xa-/!e9 Let &s s&))ose em) tale contains t%e following data.
=-/id =na-e Sa!
4== /nil 4E==
4=4 #al& 6===
4=6 Vive+ AE==
6ut/ut9 T%e res&lt for t%e aove )rogram is as given elow. eac% loc+ is t%e res&lt
of select statement.
4== /nil 4E==
4=4 #al& 6===
4=6 Vive+ AE==
4== /nil 4E==
4=4 #al& 6===
4== /nil 4E==
4=4 #al& B===
Visit: www.gcreddy.net for Testing Information
96
1. BEGIN TRAN
2. SELECT * FROM emp
3. DELETE FROM emp WHERE empid=102
4. SELECT * FROM emp
5. SAVE TRAN sp1
6. UPDATE emp SET sal=4000 WHERE empid=101
7. SELECT * FROM emp
8. ROLLBACK TRAN sp1
9. SELECT * FROM emp
10. ROLLBACK TRAN
11.SELECT * FROM emp
Visit: www.gcreddy.com for QTP Information
4== /nil 4E==
4=4 #al& 6===
4== /nil 4E==
4=4 #al& 6===
4=6 Vive+ AE==
=rrors During Transaction >rocessing
If a severe error )revents t%e s&ccessf&l com)letion of a transaction* SQL Server
a&tomatically rolls ac+ t%e transaction and frees all reso&rces %eld y t%e
transaction. If t%e client[s networ+ connection to SQL Server is ro+en* any
o&tstanding transactions for t%e connection are rolled ac+ w%en t%e networ+ notifies
SQL Server of t%e rea+. If t%e client a))lication fails or if t%e client com)&ter goes
down or is restarted* t%is also rea+s t%e connection* and SQL Server rolls ac+ any
o&tstanding connections w%en t%e networ+ notifies it of t%e rea+. If t%e client logs
off t%e a))lication* any o&tstanding transactions are rolled ac+.
If a r&n'time statement error "s&c% as a constraint violation$ occ&rs in a atc%* t%e
defa&lt e%avior in SQL Server is to roll ac+ only t%e statement t%at generated t%e
error. 2o& can c%ange t%is e%avior &sing t%e SET <ACT7ABORT statement. /fter
SET <ACT7ABORT ON is e3ec&ted* any r&n'time statement error ca&ses an
a&tomatic rollac+ of t%e c&rrent transaction. Com)ile errors* s&c% as synta3 errors*
are not affected y SET <ACT7ABORT.
Visit: www.gcreddy.net for Testing Information
97
Visit: www.gcreddy.com for QTP Information
SQL Server Secri!"
SQL Server validates &sers at two levels of sec&rity on dataase &ser
acco&nts and roles.
Login /&t%entication
Permissions Validation
T%e a&t%entication stage identifies t%e &ser &sing a login acco&nt and verifies
only t%e aility to connect wit% SQL Server. If t%e a&t%entication is s&ccessf&l* t%e
&ser is connected to SQL Server. T%e &ser t%en needs )ermissions to access
dataase on t%e server* w%ic% is done y &sing an acco&nt in eac% dataase*
ma))ed to t%e &ser login.
T%e )ermission validation stage controls t%e activities t%e &ser is allowed to
)erform in t%e SQL Server dataase.
Login 4ut8entication9
/ &ser m&st %ave a login acco&nt to connect to SQL Server. SQL
Server )rovides two ty)es of Login /&t%entications.
,indows :T /&t%entication
SQL Server /&t%entication
?indows ,T 4ut8entication
,%en &sing ,indows :T /&t%entication* t%e &ser is not re(&ired to s)ecify a
login ID or )assword to connect to SQL Server. T%e &serRs access to SQL Server is
controlled y t%e ,indows :T acco&nt* w%ic% is a&t%enticated w%en %e/s%e logs on
to t%e ,indows 5)erating System.
SQL Server 4ut8entication
,%en &sing SQL Server a&t%entication* t%e &sers m&st s&))ly t%e SQL Server
login and )assword to connect to SQL Server. T%e &sers are identified in SQL Server
y t%eir SQL Server login.
4ut8entication :ode9
SQL Server can o)erate in two sec&rity modes:
?indows ,T 4ut8entication :ode9 5nly ,indows :T /&t%entication is
allowed. >sers cannot s)ecify SQL Server /&t%entication.
:ixed :ode9 It allows &sers to connect to SQL Server &sing ,indows :T
/&t%entication or SQL Server /&t%entication.
Visit: www.gcreddy.net for Testing Information
98
Visit: www.gcreddy.com for QTP Information
"reate a 0ser Login9
83)and t%e server
83)and sec&rity
Rig%t clic+ on &!gins and select New &!gin
In t%e window dis)layed enter a name to t%e &ser &nder Name Te3to3
Clic+ t%e S+& Ser,er -.t/enticati!n o)tion &tton to )rovide t%e )assword
8nter a )assword for t%e &ser login
Clic+ O0
Visit: www.gcreddy.net for Testing Information
99
Visit: www.gcreddy.com for QTP Information
/ window called Confirm Password will e dis)layed. In t%e enter t%e
)assword again
Clic+ O0
>roviding access to a dataase for a user9
Rig%t clic+ on t%e login name and select )ro)erties
Visit: www.gcreddy.net for Testing Information
100
Visit: www.gcreddy.com for QTP Information
In t%e window dis)layed clic+ on 1atabase -ccess ta
!a+e a c%ec+ mar+ on t%e dataase for w%ic% t%e access %as to e given.
Clic+ O0
Visit: www.gcreddy.net for Testing Information
101
Visit: www.gcreddy.com for QTP Information
Granting >er-issions on a ta!e9
Rig%t clic+ on tale name and select 2r!perties
In t%e window dis)layed clic+ on 2ermissi!ns
In t%e window dis)layed ma+e a c%ec+ mar+ in t%e re(&ired action to give
)ermission to t%at action for t%e &ser on t%at tale.
Visit: www.gcreddy.net for Testing Information
102
Visit: www.gcreddy.com for QTP Information
#ACKIN$ UP AND RESTORIN$ DATA#ASES
T%e ac+&) and restore com)onent of !icrosoft? SQL Server@ 6=== )rovides an
im)ortant safeg&ard for )rotecting critical data stored in SQL Server dataases.
,it% )ro)er )lanning* yo& can recover from many fail&res* incl&ding:
!edia fail&re.
>ser errors.
Permanent loss of a server.
/dditionally* ac+ing &) and restoring dataases is &sef&l for ot%er )&r)oses* s&c% as
co)ying a dataase from one server to anot%er. #y ac+ing &) a dataase from one
com)&ter and restoring t%e dataase to anot%er* a co)y of a dataase can e made
(&ic+ly and easily.
0sing t8e =nter/rise :anager to ta2e ac2u/ of dataase9
4. 5)en t%e 8nter)rise !anager tool from t%e start men&.
6. 83)and t%e server gro&)* t%e corres)onding server* and t%e dataase.
A. Rig%t clic+ on t%e corres)onding dataase and c%oose /ll Tas+s 'K #ac+&)
DataaseP
Visit: www.gcreddy.net for Testing Information
103
Visit: www.gcreddy.com for QTP Information
B. In t%e window dis)layed clic+ on /DD &tton.
E. S)ecify t%e )at% and filename y clic+ing on t%e 5r#;se &tton.
J. clic+ O-.
5ecovering Dataase 9
4. 5)en 8nter)rise !anager Tool
6. Create a dataase for ac+&) co)y to e restored.
A. Rig%t clic+ on t%e newly created dataase and c%oose /ll Tas+s Restore
DataaseP
Visit: www.gcreddy.net for Testing Information
104
Visit: www.gcreddy.com for QTP Information
B. In t%e window dis)layed clic+ t%e dro) down &tton of 0S%ow ac+&)s of
dataase1 and select t%e dataase name t%at is to e restored.
E. Clic+ on ,O&ti#ns. ta and ma+e a c%ec+ mar+s on 0+#r!e rest#re #ver
e*istin$ )'t5'se..
Visit: www.gcreddy.net for Testing Information
105
Visit: www.gcreddy.com for QTP Information
J. Cic+ o+. If we s&ccessf&lly restored t%e dataase into t%e new dataase* we will
get t%e following message.
Visit: www.gcreddy.net for Testing Information
106
Visit: www.gcreddy.com for QTP Information
%&a!'( Ne) in SQL Server *++,
=nter/rise Data :anage-ent
In todays connected world! data and the systems that manage that
data must always be secure yet available to your users. "ith SQL
Server #$$%! users and information technology &IT' professionals
across your organi(ation will bene)t from reduced application
downtime! increased scalability and performance! and tight yet *exible
security controls. SQL Server #$$% also includes many new and
improved capabilities to help ma+e your IT sta, more productive. SQL
Server #$$% includes +ey enhancements to enterprise data
management in the following areas-
8
Manageabili
ty
8
Availability
8
Scalability
8
Security
:anageai!ity
SQL Server #$$% ma+es it simpler and easier to deploy! manage! and
optimi(e enterprise data and analytical applications. As an enterprise
data management platform! it provides a single management console
that enables data administrators anywhere in your organi(ation to
monitor! manage! and tune all of the databases and associated
services across your enterprise. It provides an extensible management
infrastructure that can be easily programmed using SQL Management
.b/ects! enabling users to customi(e and extend their management
environment and independent software vendors &IS0s' to build
additional tools and functionality to further extend the capabilities that
come out of the box.
SQL Server :anage-ent Studio
SQL Server #$$% simpli)es management by providing one integrated
management console to monitor and manage the SQL Server relational
database! as well as Integration Services! Analysis Services! 1eporting
Services! 2oti)cation Services! and SQL Server Mobile 3dition across
large numbers of distributed servers and databases. 4atabase
Visit: www.gcreddy.net for Testing Information
107
Visit: www.gcreddy.com for QTP Information
administrators can perform several tas+s at the same time! such as
authoring and executing a 5uery! viewing server ob/ects! managing an
ob/ect! monitoring system activity! and viewing online help. SQL Server
Management Studio hosts a development environment for authoring!
editing! and managing scripts and stored procedures using Transact6
SQL! Multidimensional 3xpressions! 7ML for Analysis! and SQL Server
Mobile 3dition. Management Studio is readily integrated with source
control. Management Studio also hosts tools for scheduling SQL Server
Agent /obs and managing maintenance plans to automate daily
maintenance and operation tas+s. The integration of management and
authoring in a single tool coupled with the ability to manage all types
of servers provides enhanced productivity for database administrators.
SQL Server #$$% exposes more than 8$ new measures of internal
database performance and resource usage! ranging from memory!
loc+ing! and scheduling to transactions and networ+ and dis+ I9..
These 4ynamic Management 0iews &4M0s' provide greater
transparency and visibility into the database and a powerful
infrastructure for proactive monitoring of database health and
performance.
SQL :anage-ent 6;ects
SQL Management .b/ects &SM.' is a new set of programming ob/ects
that exposes all of the management functionality of the SQL Server
database. In fact! Management Studio was built with SQL Management
.b/ects. SM. is implemented as a Microsoft .23T :ramewor+ assembly.
;ou can use SM. to automate common SQL Server administrative
tas+s! such as programmatically retrieving con)guration settings!
creating new databases! applying Transact6SQL scripts! creating SQL
Server Agent /obs! and scheduling bac+ups. The SM. ob/ect model is a
more secure! reliable! and scalable replacement for 4istributed
Management .b/ects &4M.'! which was included with earlier versions
of SQL Server.
4vai!ai!ity
Investments in high6availability technologies! additional bac+up and
restore capabilities! and replication enhancements will enable
enterprises to build and deploy highly available applications.
Innovative high6availability features such as database mirroring!
failover clustering! database snapshots! and enhanced online
operations will minimi(e downtime and help to ensure that critical
Visit: www.gcreddy.net for Testing Information
108
Visit: www.gcreddy.com for QTP Information
enterprise systems remain accessible. This section reviews these
enhancements in greater detail.
Dataase :irroring
4atabase mirroring allows continuous streaming of the transaction log
from a source server to a single destination server. In the event of a
failure of the primary system! applications can immediately reconnect
to the database on the secondary server. The secondary instance
detects failure of the primary server within seconds and accepts
database connections immediately. 4atabase mirroring wor+s on
standard server hardware and re5uires no special storage or
controllers. :igure < shows the basic con)guration of database
mirroring.
Figure 19 &asic "onfiguration of Dataase :irroring
Fai!over "!ustering
:ailover clustering is a high6availability solution that exploits Microsoft
"indows =lustering Services to create fault6tolerant virtual servers that
provide fast failover in the event of a database server failure. In SQL
Server #$$%! support for failover clustering has been extended to SQL
Server Analysis Services! 2oti)cation Services! and SQL Server
replication. The maximum number of cluster nodes has been increased
to eight. SQL Server failover clustering is now a complete fault6tolerant
server solution.
4vai!ai!ity Feature Dataase :irroring Fai!over "!ustering
/&tomatic 9ailover 2es 2es
Trans)arent Client Redirection 2es* a&to'redirect 2es* reconnect to same IP
Visit: www.gcreddy.net for Testing Information
109
Visit: www.gcreddy.com for QTP Information
4vai!ai!ity Feature Dataase :irroring Fai!over "!ustering
Im)act on 5verall T%ro&g%)&t :o im)act to minimal :o im)act
Mero ,or+ Loss 2es 2es
Re(&ires Certified <ardware :o 2es
Provides Red&ndant Data 2es :o
Dataase Sna/s8ots
SQL Server #$$% introduces the ability for database administrators to
create instant! read6only views of a database. This database snapshot
provides a stable view without the time or storage overhead of
creating a complete copy of the database. As the primary database
diverges from the snapshot! the snapshot adds its own copy of pages
as they are modi)ed. As a result! the snapshot may be used to 5uic+ly
recover from an accidental change to a database by simply reapplying
the original pages from the snapshot to the primary database.
Fast 5ecovery
SQL Server #$$% improves the availability of SQL Server databases
with a new and faster recovery option. >sers can reconnect to a
recovering database after the transaction log has been rolled forward.
3arlier versions of SQL Server re5uired users to wait until incomplete
transactions had rolled bac+! even if the users did not need to access
the a,ected parts of the database.
Dedicated 4d-inistrator "onnection
SQL Server #$$% introduces a dedicated administrator connection to
access a running server even if the server is not responding or is
otherwise unavailable. This allows you to execute diagnostic functions
or Transact6SQL statements so you can troubleshoot problems on a
server. The connection is activated by members of the sysadmin )xed
server role and is only available through the SQL=M4 command
prompt tool either locally or from a remote computer.
6n!ine 6/erations (Index 6/erations and 5estore)
The ability to create! rebuild! or drop an index online is an enhanced
feature of SQL Server #$$% that augments the indexing capabilities of
earlier versions of SQL Server. The online index option allows
concurrent modi)cations &updates! deletes! and inserts' to the
underlying table or clustered index data and any associated indexes
during index data de)nition language &44L' execution. "ith support for
Visit: www.gcreddy.net for Testing Information
110
Visit: www.gcreddy.com for QTP Information
online index operations! you can add indexes without interfering with
access to tables or other existing indexes. Additionally! the server
wor+load allows index operations to ta+e advantage of parallel
processing. SQL Server #$$% also introduces the ability to perform a
restore operation while an instance of SQL Server is running. .nline
restoration capabilities improve the availability of SQL Server because
only the data that is being restored is unavailable. The rest of the
database remains online and available. 3arlier versions of SQL Server
re5uire that you bring a database o?ine before you restore the
database.
5e/!ication
1eplication is designed to increase data availability by distributing the
data across multiple database servers. Availability is increased by
allowing applications to scale out the SQL Server read wor+load across
databases. SQL Server #$$% o,ers enhanced replication using a new
peer6to6peer model that provides a new topology in which databases
can be synchroni(ed transactionally with any identical peer database.
Sca!ai!ity
Scalability advancements such as table partitioning! snapshot isolation!
and @A6bit support will enable you to build and deploy your most
demanding applications using SQL Server #$$%. The partitioning of
large tables and indexes signi)cantly enhances 5uery performance
against very large databases.
Ta!e and Index >artitioning
Table and index partitioning eases the management of large databases
by facilitating the management of the database in smaller! more
manageable chun+s. "hile the concept of partitioning data across
tables! databases! and servers is not new to the world of databases!
SQL Server #$$% provides a new capability for the partitioning of tables
across )legroups in a database. Bori(ontal partitioning allows for the
division of a table into smaller groupings based on a partitioning
scheme. Table partitioning is designed for very large databases! from
hundreds of gigabytes to terabytes and beyond.
Sna/s8ot Iso!ation
After data is copied! transformed! and archived to an analysis6oriented
database! it must be maintained and9or rebuilt periodically. >sers
certainly bene)t from loo+ing at a transactionally consistent version of
the databaseC however! the version of the data that they are viewing is
Visit: www.gcreddy.net for Testing Information
111
Visit: www.gcreddy.com for QTP Information
no longer current. It can ta+e many hours to build and index the data
and that might not be what the user really needs. This is where
snapshot isolation is helpful. The snapshot isolation level allows users
to access the last row that was committed by using a transactionally
consistent view of the database. This new isolation level provides the
following bene)ts-
8
Increased data availability for read6only applications.
8
2onbloc+ing read operations allowed in an online transaction
processing &.LTD' environment.
8
Automatic mandatory con*ict detection for write transactions.
8
Simpli)ed migration of applications from .racle to SQL Server.
5e/!ication :onitor
1eplication Monitor is a tool that sets a new standard for ease of use in
managing complex data replication operations with its intuitive user
interface and wealth of data metrics.
Su//ort for +%'it Syste- Itaniu- 2 and x+%
.ptimi(ed for the Intel Itanium processor! SQL Server &@A6bit' ta+es
advantage of advanced memory addressing capabilities for essential
resources such as bu,er pools! caches! and sort heaps! reducing the
need to perform multiple I9. operations to bring data in and out of
memory from dis+. Ereater processing capacity without the penalties
of I9. latency opens the door to new levels of application scalability.
"indows Server #$$F x@A provides high performance for both F#6bit
and @A6bit applications on the same system. The underlying
architecture is based on @A6bit extensions to the industry6standard xG@
instruction set! allowing todays F#6bit applications to run natively on
x@A processors. At the same time! new @A6bit applications are
executed in @A6bit mode! which processes more data per cloc+ cycle!
allows greater access to memory! and speeds numeric calculations.
The result is a platform that ta+es advantage of the existing wealth of
F#6bit applications while also providing a smooth migration path to @A6
bit computing.
Security
SQL Server #$$% ma+es signi)cant enhancements to the security
model of the database platform! with the intention of providing more
precise and *exible control to enable tighter security of the data. A
Visit: www.gcreddy.net for Testing Information
112
Visit: www.gcreddy.com for QTP Information
considerable investment has been made in a number of features to
provide a high level of security for your enterprise data including the
following-
8
3nforcing policies for SQL Server login passwords in the
authentication space.
8
Droviding for more granularity in terms of specifying permissions at
various scopes in the authori(ation space.
8
Allowing for the separation of owners and schemas in the security
management space.
4ut8ori.ation
A new security model in SQL Server #$$% allows administrators to
manage permissions at a granular level and at a designated scope!
ma+ing management of permissions easier as well as ensuring that the
principle of least privileges is upheld. SQL Server #$$% lets you specify
a context under which statements in a module execute. This feature
also acts as an excellent mechanism for granular permission
management.
4ut8entication
SQL Server #$$% clustering supports Herberos authentication against a
SQL Server #$$% virtual server. Administrators can specify Microsoft
"indows6style policies on standard logins so that a consistent policy is
applied across all accounts in the domain.
,ative =ncry/tion
SQL Server #$$% supports encryption capabilities within the database
itself! fully integrated with a +ey management infrastructure. Iy
default! client9server communications are encrypted. To centrali(e
security assurance! server policy can be de)ned to re/ect unencrypted
communications.
SQL Server and Trustwort8y "o-/uting
The Microsoft Trustworthy =omputing initiative outlines a framewor+
that de)nes the steps necessary to support more secure computing as
well as measures that help you deploy and maintain a more secure
environment. These steps help to protect the con)dentiality! integrity!
and availability of data and systems at every phase of the software life
cycleJfrom design! to delivery! to maintenance. To uphold the four
Visit: www.gcreddy.net for Testing Information
113
Visit: www.gcreddy.com for QTP Information
tenets of the Trustworthy =omputing initiative! Microsoft and the SQL
Server team have addressed the following issues-
8
Sec!re $y desi%n. The SQL Server development team conducted
multiple security audits and spent more than two months studying
SQL Server components and the interaction between them. :or each
potential security threat! the team did a threat analysis to evaluate
the issue and completed additional design and testing wor+ to
neutrali(e potential security issues. Iecause of these design e,orts!
SQL Server #$$% includes many new server security features.
8
Sec!re $y de&a!lt. >pon installation! SQL Server #$$% chooses the
right set of con)guration values for all setup options! ensuring that
when a new system is installed! it will be in a secure state by default.
8
Sec!re in deploy#ent. Microsoft has created content to help
organi(ations deploy SQL Server using the proper security credentials
and to fully understand the steps and permissions re5uired. SQL
Server deployment tools provide the information necessary to
understand the decisions you need to ma+e during deployment.
Security updates are easy to )nd and installJand if you choose the
option! the updates install automatically. Tools are also available to
help you assess and manage security ris+s across organi(ations.
Deve!o/er >roductivity
SQL Server #$$% includes many new technologies that bring signi)cant
increases in developer productivity. :rom .23T :ramewor+ support to
tight integration with 0isual Studio! these features provide developers
with the ability to more easily create secure! robust database
applications at a lower cost. SQL Server #$$% enables developers to
ta+e advantage of existing s+ills across a variety of development
languages while providing an end6to6end development environment for
the database. 2ative 7ML capabilities also allow developers to build
new classes of connected applications across any platform or device.
3nhancements for developer productivity include the following-
8
3xpanded language
support
8
Improved development
tools
Visit: www.gcreddy.net for Testing Information
114
Visit: www.gcreddy.com for QTP Information
8
3xtensibility
8
Improved data access
8
7ML and "eb services
8
Application framewor+
=x/anded Language Su//ort
Iecause the common language runtime &=L1' is hosted in the
database engine! developers can choose from a variety of familiar
languages to develop database applications! including Transact6SQL!
Microsoft 0isual Iasic .23T! and Microsoft 0isual =K .23T. Additionally!
=L1 hosting provides developers with increased *exibility with user6
de)ned types and functions. The =L1 also provides opportunities to
use non6Microsoft code for rapid database application development.
"L57G,=T Fra-ewor2 Integration
"ith the release of SQL Server #$$%! database programmers can now
ta+e full advantage of the Microsoft .23T :ramewor+ class library and
modern programming languages to implement functionality within the
server. >sing =L1 integration! you can code your stored procedures!
functions! and triggers in the .23T :ramewor+ language of your choice.
Microsoft 0isual Iasic .23T and the =K programming language both
o,er ob/ect6oriented constructs! structured exception handling! arrays!
namespaces! and classes. Additionally! the .23T :ramewor+ provides
thousands of classes and methods that have extensive built6in
capabilities that you can easily use on the server side. Many tas+s that
were aw+ward or diLcult to perform in Transact6SQL can be better
accomplished by using managed codeC additionally! two new types of
database ob/ectsJaggregates and user6de)ned typesJare available.
;ou can now better use the +nowledge and s+ills that you have already
ac5uired to write in6process code. In short! SQL Server #$$% enables
you to extend the database server to more easily perform appropriate
computation and operations on the bac+ end.
This integration between SQL Server and the =L1 provides several
ma/or bene)ts-
8
Enhanced pro%ra##in% #odel' Drogramming languages that are
compatible with the .23T :ramewor+ are in many respects richer
than Transact6SQL! o,ering constructs and capabilities that were
previously not available to SQL Server developers.
Visit: www.gcreddy.net for Testing Information
115
Visit: www.gcreddy.com for QTP Information
8
Enhanced sa&ety and sec!rity' Managed code runs in a =L1
environment! hosted by the database engine. This allows .23T
:ramewor+ database ob/ects to be safer and more secure than the
extended stored procedures available in earlier versions of SQL
Server.
8
User(de)ned types and a%%re%ates' Two new database ob/ects
that expand the storage and 5uerying capabilities of SQL Server are
enabled by hosting the =L1.
8
Co##on de"elop#ent en"iron#ent' 4atabase development is
integrated into the Microsoft 0isual Studio #$$% development
environment. ;ou can use the same tools for developing and
debugging database ob/ects and scripts that you use to write middle6
tier or client6tier .23T :ramewor+ components and services.
8
*er&or#ance and scala$ility' Iecause managed code compiles to
native code prior to execution! you can achieve signi)cant
performance increases in some scenarios.
Iy using languages such as 0isual Iasic .23T and =K! you can
capitali(e on =L1 integration to write code that has more complex logic
and is more suited for computation tas+s. Additionally! 0isual Iasic
.23T and =K o,er ob/ect6oriented capabilities such as encapsulation!
inheritance! and polymorphism. ;ou can easily organi(e related code
into classes and namespaces! which means that you can more easily
organi(e and maintain your code investments when you are wor+ing
with large amounts of code. The ability to logically and physically
organi(e code into assemblies and namespaces is a huge bene)t that
allows you to better )nd and relate di,erent pieces of code in a large
database implementation.
Managed code is more eLcient than Transact6SQL at processing
numbers and managing complicated execution logic! and provides
extensive support for string handling! regular expressions! and so on.
Also! with the functionality that is available in the .23T :ramewor+
class library! you have full access to thousands of prebuilt classes and
routines that you can access easily from any stored procedure! trigger!
or user6de)ned function. 3verything from improved string6handling
functions! math functions! date operations! access to system
resources! advanced encryption algorithms! )le access! image
processing! and 7ML data manipulation is easily accessible from
managed stored procedures! functions! triggers! and aggregates.
Visit: www.gcreddy.net for Testing Information
116
Visit: www.gcreddy.com for QTP Information
.ne of the ma/or bene)ts of managed code is type safety. Iefore
managed code is executed! the =L1 performs several chec+s through a
process +nown as veri)cation to ensure that the code is safe to run. :or
example! the code is chec+ed to ensure that memory is not read that
has not been written to.
Transact'SQL =n8ance-ents
Transact6SQL has long been the basis for all SQL Server
programmability. SQL Server #$$% provides many new language
capabilities for developing scalable database applications. These
enhancements include error handling! new recursive 5uery capabilities!
and support for new SQL Server 4atabase 3ngine capabilities.
Transact6SQL enhancements in SQL Server #$$% increase your
expressive powers in 5uery writing! allowing you to improve the
performance of your code and extend your error management
capabilities. The continuous e,ort that is being put into enhancing
Transact6SQL shows a )rm belief in its signi)cant role in SQL Server.
I-/roved Deve!o/-ent Too!s
4evelopers will be able to use one development tool for Transact6SQL!
7ML! Multidimensional 3xpressions &M47'! and 7ML for Analysis
&7MLA'. Integration with the 0isual Studio development environment
will provide more eLcient development and debugging of line6of6
business and business intelligence &II' applications.
&usiness Inte!!igence Deve!o/-ent Studio
The Iusiness Intelligence 4evelopment Studio is a common
development environment for building II solutions based on 0isual
Studio including a database engine! analysis services! and reporting
services. >se the Iusiness Intelligence 4evelopment Studio graphical
user interface &E>I' to design SQL Server Integration Services &SSIS'
pac+ages for data6management applications. SSIS pac+ages are
designed! developed! and debugged in Iusiness Intelligence
4evelopment Studio by dragging tas+s from the toolbox! setting their
properties! and connecting tas+s with precedence constraints. :igure #
shows the interface in 0isual Studio for Iusiness Intelligence
4evelopment Studio.
Visit: www.gcreddy.net for Testing Information
117
Visit: www.gcreddy.com for QTP Information
Figure 29 &usiness Inte!!igence Deve!o/-ent Studio Interface in *isua! Studio
*isua! Studio Integration
SQL Server #$$% and 0isual Studio #$$% together provide deeper
levels of integration between the database and the application
development environment than ever before. 4evelopers now have the
ability to create =L1 stored procedures! functions! user6de)ned types!
and user6de)ned aggregates directly from within the 0isual Studio
development environment. They can deploy these new database
ob/ects directly from 0isual Studio without having to switch tools.
0isual Studio #$$% directly supports all of the new SQL Server data
types! such as native 7ML. ;ou can also add your =L1 database ob/ects
to the same source control system that you use for all you 0isual
Studio pro/ects! thus providing an even greater level of integration and
security to your development processes.
"ross'Tier and "ross'Language Deugging
SQL Server #$$% and 0isual Studio #$$% together provide even deeper
integration in the area of application debugging. The combination lets
you seamlessly debug both =L1 and Transact6SQL code using the same
0isual Studio debugging interface! and allows you to debug from =L1
to Transact6SQL and bac+ again! regardless of the location of the code!
whether it is on the developer computer or stored in the SQL Server
database.
Visit: www.gcreddy.net for Testing Information
118
Visit: www.gcreddy.com for QTP Information
=xtensii!ity
User(+e)ned Types and ,%%re%ates
>ser6de)ned types in SQL Server #$$% are not an ob/ect relational
extensibility mechanism. They are a way to extend the scalar type
system of the database. The scalar type system includes the columnar
types that ship with SQL Server &types such as int! nvarchar!
uni5ueidenti)er! and so on'. "ith user6de)ned types! you can de)ne
your own type that can be used for column de)nitions! for example.
=reate a user6de)ned type if your type really is an atomic value that is
appropriate to be modeled as a column.
>se user6de)ned types if you need to de)ne your own scalar type.
3xample scenarios for such types include custom date9time data types
in various calendars! and currency data types. "ith user6de)ned types!
you can create a single ob/ect that exposes all the behaviors that are
available on the type! and encapsulate! or hide! the underlying data
that is stored by the type. 3veryone that needs to access the data has
to use the user6de)ned type programmatic interface. Ta+ing advantage
of existing functionality in the .23T :ramewor+ &such as the
internationali(ation or calendar functionality' is another strong reason
to consider implementing your type as a user6de)ned type.
In a number of scenarios! you may need to perform aggregations over
data. This includes performing statistical calculations! such as avg!
stddev! and so on. If the desired aggregation function is not directly
supported as a built6in aggregate function! you have three ways to
perform a custom aggregation in SQL Server #$$%-
8
"rite the aggregation as a user6de)ned
aggregate.
8
"rite the aggregate using a =L1 stored
procedure.
8
>se a server6side cursor.
SQL -ana%e#ent O$.ects
SQL Management .b/ects &SM.' is the management ob/ect model for
SQL Server #$$%. SM. represents signi)cant design and architectural
improvements for the SQL Server management ob/ect model. It is a
simple6to6use but rich ob/ect model that is based on .23T :ramewor+
managed code. SM. is the primary tool for developing database
Visit: www.gcreddy.net for Testing Information
119
Visit: www.gcreddy.com for QTP Information
management applications using .23T :ramewor+. SM. is used by
every dialog box in SQL Server Management Studio! and every
administrative action that you can perform in SQL Server Management
Studio you can also accomplish by using SM..
The new SM. ob/ect model and the Microsoft "indows Management
Instrumentation &"MI' application programming interfaces &ADIs'
replace SQL64M.. "here possible! SM. incorporates similar ob/ects as
SQL64M. for ease of use. ;ou can still use SQL Server #$$% with SQL6
4M.! but SQL64M. will not be updated to manage features that are
speci)c to SQL Server #$$%.
,nalysis -ana%e#ent O$.ects
Analysis Management .b/ects &AM.' allows client applications to
access the range of administrative commands and capabilities
available to Analysis Services using an ob/ect library that can provide
ob/ect6level validation capabilities! instead of having to manually
generate 44L scripts for Analysis Services commands and the often6
lengthy contents of the Analysis Services Scripting Language &ASSL'
.b/ect4e)nition element. Applications using AM. can either connect
and wor+ directly with ob/ects on an Analysis Services instance! or
create such ob/ects without an existing connection and persist the
metadata for later deployment. AM. also MwrapsM ASSL commands and
elements.
I#pro"ed +ata ,ccess and /e$ Ser"ices
In SQL Server #$$%! you can develop 7ML "eb services in the
database tier! ma+ing SQL Server an BTTD listener. This provides a new
type of data access capability for applications that are centrali(ed
around "eb services. In SQL Server #$$%! you can use BTTD to access
SQL Server directly! without using a middle6tier listener such as
Microsoft Internet Information Services &IIS'. SQL Server exposes a "eb
service interface to allow the execution of SQL statements and
invocation of functions and procedures. Query results are returned in
7ML format and can ta+e advantage of the 0isual Studio "eb services
infrastructure.
,+O'NET 0'12,+O-+'NET
Much is new in the next version of A4..23T. :rom new support for
5uery change noti)cations to Multiple Active 1esult Sets &MA1S'!
A4..23T evolves dataset access and manipulation to achieve greater
scalability and *exibility.
Visit: www.gcreddy.net for Testing Information
120
Visit: www.gcreddy.com for QTP Information
Query ,otification
SQL Server #$$% introduces noti)cation support for SQL Server
5ueries. ;ou can use this support to send a command to SQL Server
and to re5uest that a noti)cation be generated if executing the same
command again produces di,erent results from those obtained initially.
;ou accomplish this by using a dependency ob/ect that detects when
the underlying data is changed. =ommands that are sent to the server
through any of the client ADIs such as A4..23T! .L3 4I! .pen
4atabase =onnectivity &.4I='! Microsoft Active7 4ata .b/ects &A4.'!
or Simple .b/ect Access Drotocol &S.AD' may include a tag that
re5uires a noti)cation. :or each statement that is executed as part of
the re5uest! the server creates a noti)cation subscription that )res
once for each statement that is included in the re5uest. 2oti)cations
are delivered through a SQL Service Iro+er 5ueue that applications can
poll! and use activation services or bloc+ing statements that return
whenever the noti)cations are available. Query noti)cations are useful
for enabling the caching of results in applications such as database6
driven "eb sites. :igure F shows the 5uery noti)cation process.
Figure #9 Query ,otification
:45S
Multiple Active 1esult Sets &MA1S' provides the means to have more
than one pending re5uest per connection! in particular to have more
than one default result set open per connection. 4efault result sets are
forward6only! read6only result sets. :or default result sets! the client
drivers transparently retrieve the data in large chun+s &Tabular 4ata
Stream bu,er6si(ed chun+s' so that application re5uests are satis)ed
without a round trip to the server &as in the case of server cursors'. The
application can use a simple row6at6a6time programming model without
compromising performance. The MA1S feature removes the current
restriction in which an open default result set bloc+s the driver from
sending re5uests to the server until the entire result set is consumed.
Visit: www.gcreddy.net for Testing Information
121
Visit: www.gcreddy.com for QTP Information
Trans/arent Fai!over for Data :irroring
SQL Server #$$% supports a Mhot spareM capability through database
mirroring. If a SQL Server instance fails! wor+ can be shifted to the
bac+up server automatically. This re5uires an instance to witness the
failover +nown as &not surprisingly' the witness instance. Bot spare
scenarios re5uire that existing client connections must M+nowM to fail
over &establish a connection with the new server instance'! as well. It is
suboptimal for client connections to produce an error on the next
attempted access and to have to be manually Mfailed overM by client
programming. S5l=lient in A4..23T #.$ supports client failover without
special programming of the application program.
J:L Su//ort
Advancements such as the native 7ML data type and 7Query help
organi(ations seamlessly connect internal and external systems. SQL
Server #$$% supports both relational and 7ML data natively! so
enterprises can store! manage! and analy(e data in the format that
best suits their needs. Support for existing and emerging open
standards such as Bypertext Transfer Drotocol &BTTD'! 7ML! Simple
.b/ect Access Drotocol &S.AD'! 7Query! and 7ML Schema de)nition
language &7S4' also facilitate communication across extended
enterprise systems.
J:L Data Ty/e
7ML can model complex dataC it is not limited to the scalar types that
are supported by SQL Server. As such! a string6based! built6in data type
such as char or varchar does not suLce to ma+e full and e,ective use
of the power and the numerous advantages of 7ML. :or example! if
7ML is stored as a string! you can insert or select an entire document!
or even retrieve contiguous bytes from it! but you cannot 5uery into
the contents of the document itself. Iy providing the 7ML data type!
SQL Server #$$% allows you to 5uery portions of an 7ML document!
validate that the document conforms to an 7ML schema! and even
modify the contents of the 7ML document in place. It also integrates
traditional! relational data with data in unstructured or semistructured
7ML documents in ways that are not possible with SQL Server #$$$. In
SQL Server #$$%! 7ML data is stored as binary large ob/ects &IL.Is' in
an internal representation that allows eLcient reparsing and some
compression.
A collection of 7ML schemas can be associated with a column of type
7ML. This provides validation for constraints! inserts! and updates! and
typing of values inside stored 7ML data! as well as optimi(ations for
Visit: www.gcreddy.net for Testing Information
122
Visit: www.gcreddy.com for QTP Information
storage and 5uery processing. SQL Server #$$% also provides several
44L statements for managing schemas on the server.
JQuery
The 7ML Query Language! or 7Query! is an intelligent and robust
language that is optimi(ed for 5uerying all types of 7ML data. "ith
7Query! you can run 5ueries against variables and columns of the 7ML
data type using the latters associated methods. As with many 7ML
standards! the "orld "ide "eb =onsortium &"F=' oversees the
development of 7Query. 7Query evolved from a 5uery language called
Quilt! which was itself based on a variety of other 5uery languages
such as the 7ML Dath Language &7Dath' version <.$! 7ML Query
Language &7QL'! and SQL. It also contains 7Dath #.$ as a subset.
Therefore! if you have experience using 7Dath <.$! you can capitali(e
on your s+ills and do not have to learn an entirely new 5uery language.
There are! however! signi)cant enhancements that go beyond 7Dath
<.$! such as typing! special functions! and support for better iteration!
sorting of results! and construction.
SQL Server #$$% ships with deep 7Query capabilities that allow for
7ML ob/ect manipulation in the data tier. It supports a statically typed
subset of the 7Query <.$ "or+ing 4raft of 2ovember <%! #$$F.
?e Services Su//ort
In SQL Server #$$%! you can develop 7ML "eb services in the
database tier! ma+ing SQL Server an BTTD listener. This provides a new
type of data access capability for applications that are centrali(ed
around "eb services. In SQL Server #$$%! you can use BTTD to access
SQL Server directly without using a middle6tier listener such as
Microsoft Internet Information Services &IIS'. SQL Server exposes a "eb
service interface to allow the execution of SQL statements and
invocation of functions and procedures. Query results are returned in
7ML format and can ta+e advantage of the 0isual Studio "eb services
infrastructure.
J:L for 4na!ysis Services
7ML for Analysis Services &7MLA' is the native! standards6based
protocol for communicating with the Analysis Services server. 2ew
+inds of applications are enabled and easy to developJapplications
that integrate analytics with operations in real time. "ith 7MLA as the
native protocol! Analysis Services clients can be con)gured to have a
(ero footprint! and each server is automatically a "eb service. A light6
footprint "inF# layer is available for bac+ward compatibility with tools
Visit: www.gcreddy.net for Testing Information
123
Visit: www.gcreddy.com for QTP Information
that wor+ with Analysis Services #$$$ on .L3 4I for .LAD! A4.M4!
and A4.M4.23T. Many users will continue to use the A4.M4.23T
ob/ect model to build custom applications on Analysis Services.
4//!ication Fra-ewor2
SQL Server #$$% introduces a new SQL Server application framewor+
that includes Service Iro+er! 2oti)cation Services! SQL Server Mobile!
and SQL Server 3xpress. Service Iro+er is a distributed application
framewor+ that provides reliable asynchronous messaging at the
database6to6database level.
Service &ro2er
.ver the last <$ years! the proliferation of e6commerce applications
has created the need for increased wor+*ow management across
database applications. "hen an online customer places an order for a
boo+! this order needs to commit transactions into the inventory!
shipping! and credit card systems! and needs to send an order
con)rmation using another "eb application. "aiting for each of these
processes to happen in order does not scale well. SQL Server #$$%
provides a new scalable architecture for building asynchronous
message routing. :igure A outlines the Service Iro+er architecture.
Figure %9 Service &ro2er 4rc8itecture
The Service Iro+er technology allows internal or external processes to
send and receive streams of reliable! asynchronous messages by using
Visit: www.gcreddy.net for Testing Information
124
Visit: www.gcreddy.com for QTP Information
extensions to normal Transact6SQL data manipulation language.
Messages are sent to a 5ueue in the same database as the sender! to
another database in the same instance of SQL Server! or to another
instance of SQL Server either on the same server or on a remote
server.
Microsoft SQL Server 2oti)cation Services is a platform for developing
and deploying applications that generate and send noti)cations to
users. 2oti)cations are personali(ed! timely messages that can be sent
to a variety of devices.
2oti)cations re*ect subscriber preferences. The subscriber enters a
subscription to express an interest in information! such as M2otify me
when the stoc+ price of Adventure "or+s reaches N8$.$$!M or M2otify
me when the strategy document my team is writing is updated.M
A noti)cation can be generated and sent to the user as soon as a
triggering event occurs! or it can be generated and sent on a
predetermined schedule that the user speci)es. The users subscription
speci)es when the noti)cation should be generated and sent.
2oti)cations can be sent to a various devices! such as to a users
mobile phone! personal digital assistant &D4A'! Microsoft "indows
Messenger! or e6mail account. Iecause these devices often accompany
the user! noti)cations are ideal for sending high6priority information.
SQL Server :oi!e =dition
SQL Server #$$$ shipped with SQL Server #$$$ "indows =3 3dition!
which is now SQL Server Mobile 3dition version F.$. A number of new
+ey features in SQL Server Mobile 3dition relate to developers-
8
;ou can create a SQL Server Mobile 3dition database on the des+top
or on the device! directly from SQL Server Management Studio. ;ou
can also manipulate the schema of the SQL Server Mobile 3dition
database directly from Management Studio! regardless of whether
the database resides on the mobile device or on the des+top. ;ou can
use SQL Server Management Studio to run 5ueries that target a SQL
Server Mobile 3dition database on the device or on the des+top. ;ou
can also ta+e advantage of new SQL Server Mobile 3dition features
that include an 7ML showplan rendered in a graphical user interface
format /ust li+e native SQL Server and the ability to use 5uery hints
to override the 5uery optimi(er in SQL Server Mobile 3dition. :or the
)rst time! you can control the optimi(ation plan on a device.
Visit: www.gcreddy.net for Testing Information
125
Visit: www.gcreddy.com for QTP Information
8
;ou can now code against SQL Server Integration Services &SSIS'
ob/ects to exchange data.
8
The new S5l=e1esult set is derived from the SQL1esult set that is in
SQL Server #$$%. This allows SQL Server Mobile 3dition to have a
true! scrollable! and updateable cursor. It also allows binding to data
ob/ects that are on devices.
8
;ou can code an application to synchroni(e data while leaving the
main application open and you can have two separate applications
access the same database on the device at the same time.
8
;ou can get noti)cations that you can code into status bars that will
give the synchroni(ation status. Dreviously! you had no way to +now
how far synchroni(ation had progressed! to notify users that a device
had not stopped responding.
8
;ou can maintain the small si(e of the database through a much
more aggressive page reclamation policy.
8
;ou can share parameteri(ed 5uery code with SQL Server syntax.
SQL Server =x/ress
More than ever! developers are ma+ing the most of relational
databases to provide a rich end6user experience. Drotecting and
managing information inside these applications is critical. Microsoft
SQL Server 3xpress helps developers build robust and reliable
applications by providing a free! easy6to6use! and robust database. Too
often! database systems are overly complex for building simple
applications. Microsoft 0isual Studio #$$% and SQL Server 3xpress
reduce this complexity by providing a simple but powerful
development environment for building data6driven applications.
4evelopers can design schemas! add data! and 5uery local databases!
all inside the 0isual Studio #$$% environment. If developers need more
advanced database features! then SQL Server 3xpress can be
seamlessly upgraded to more sophisticated versions of SQL Server.
:igure % shows the Query 3ditor interface in SQL Server 3xpress
Manager.
Visit: www.gcreddy.net for Testing Information
126
Visit: www.gcreddy.com for QTP Information
Figure )9 T8e Query =ditor in SQL Server =x/ress :anager
A new graphical user interface tool called SQL Server 3xpress Manager
&7M' is freely available as a separate "eb download. 7M allows easy
database management and 5uery analysis capabilities! has a small
download si(e! and will be freely redistributable. 7M supports
connections to SQL Server 3xpress and other SQL Server #$$%
editions! SQL Server #$$$! and MS43 #$$$. A simpli)ed connection
dialog box guides the user through the selection of the instance and
the authentication methods to be used. Ioth local and remote
connections are possible using 7M. .b/ect 3xplorer enumerates and
displays the common ob/ects used! such as the instance! tables! stored
process! and so on! in a hierarchical manner and helps the user
visuali(e access to the database.
All database management functionalities are available by invo+ing the
right6clic+ context menu from .b/ect 3xplorer. Some of the database
management options to be exposed include creating and modifying
databases! tables! logins! and users. Many of these common database
operations are available as tas+ wi(ards that guide the user through
the process! while many others are available as tabbed window
documents. :or instance! 7M provides a 2ew93dit 4atabase document
for creating new databases and editing existing databases.
Many database users prefer to manage their servers using Transact6
SQL! because this approach o,ers )ner6grained control than using the
graphical user interface. The Query 3ditor in 7M lets users develop and
execute Transact6SQL statements and scripts. The Query 3ditor has
rich features such as +eyword color6coding and a results pane that
Visit: www.gcreddy.net for Testing Information
127
Visit: www.gcreddy.com for QTP Information
returns results in a data grid. 3rror messages! if any! are also shown in
the results pane.
&usiness Inte!!igence
SQL Server #$$% furthers Microsoft leadership in the area of business
intelligence &II' through innovations in scalability! data integration!
development tools! and rich analytics. SQL Server #$$% enables
scalable II by putting critical! timely information in the hands of
employees across your organi(ation. :rom the =3. to the information
wor+er! employees will be able to 5uic+ly and easily harness data to
ma+e better decisions faster. The comprehensive integration! analysis!
and reporting capabilities of SQL Server #$$% enable companies to
extend the value of their existing applications! regardless of the
underlying platform. II features include enhancements in the following
areas-
8
An end6to6end integrated business intelligence
platform
8
Integration Services
8
Analysis Services
8
1eporting Services
8
Integration with the Microsoft .Lce System
=nd'to'=nd Integrated &usiness Inte!!igence >!atfor-
SQL Server #$$% is a complete II platform that provides the features!
tools! and functionality to build both classic and innovative +inds of
analytical applications. The following information introduces the tools
that you will use to build an analytical application! and highlights new
functionality that ma+es it easier than ever to build and manage
complex II systems.
The SQL Server #$$% II toolset delivers end6to6end II application
integration-
8
+esi%n' Iusiness Intelligence 4evelopment Studio is the )rst
integrated development environment designed for the II developer.
Iuilt on 0isual Studio #$$%! Iusiness Intelligence 4evelopment
Studio delivers a rich! integrated! professional development platform
Visit: www.gcreddy.net for Testing Information
128
Visit: www.gcreddy.com for QTP Information
for II system developers. 4ebugging! source control! and script and
code development are available for all components of the II
platform.
8
Inte%rate' SQL Server Integration Services &SSIS' has been rewritten
to perform complex data integration! transformation! and synthesis
at high speed for very large data volumes. Iusiness Intelligence
4evelopment Studio ma+es building and debugging pac+ages
positively fun. Integration Services! Analysis Services! and 1eporting
Services wor+ together to present a seamless view of data from
heterogeneous sources.
8
,naly3e' Microsoft 4ata Mining has always been easy to use. 2ow it
is even better with the addition of important new algorithms!
including Association 1ules! Time Series! 1egression Trees! Se5uence
=lustering! 2eural 2etwor+! and 2aOve Iayes. SQL Server #$$% blurs
the lines between relational and multidimensional databases. ;ou can
store data in the relational database! in the multidimensional
database! or use the new Droactive =ache feature to get the best of
both worlds. Important new analytical capabilities have been added
to Analysis Services cubes as wellC these include +ey performance
indicator &HDI' framewor+! M47 scripts! and other built6in advanced
business analytics. The 1eporting Services report delivery and
management framewor+ enables easy distribution of complex
analytics to the widest possible audience.
8
Report' 1eporting Services extends the Microsoft II platform to
reach the business user who needs to consume the analysis.
1eporting Services is an enterprise6managed reporting environment!
embedded and managed through "eb services. 1eports can be
personali(ed and delivered in a variety of formats! with a range of
interactivity and printing options. =omplex analyses can reach a
broad audience through the distribution of reports as a data source
for downstream II. 2ew with SQL Server #$$% is the reporting tool!
1eport Iuilder.
8
-ana%e' SQL Server Management Studio integrates the
management of all SQL Server #$$% components. II practitioners will
bene)t from this extension of the server abilities you expect from the
relational engineJscalability! reliability! availability! programmability!
and so onJto the full set of II platform components.
Integration Services
SQL Server #$$% includes a redesigned enterprise data extraction!
transformation! and loading &3TL' platform! called SQL Server
Visit: www.gcreddy.net for Testing Information
129
Visit: www.gcreddy.com for QTP Information
Integration Services &SSIS'. SSIS enables organi(ations to more easily
integrate and analy(e data from multiple heterogeneous information
sources. Iy analy(ing data across an array of operational systems!
organi(ations may gain a competitive edge through a holistic
understanding of their business.
=nter/rise =TL >!atfor-
This new platform is the successor to the popular feature in SQL Server
#$$$ called 4ata Transformation Services &4TS'. SSIS is completely
new for SQL Server #$$%. SSIS provides the breadth of features and
very high6scale performance that is necessary to build enterprise6class
3TL applications. SSIS is fully programmable! embeddable! and
extensibleJcharacteristics that ma+e it an ideal 3TL platform.
&eyond Traditiona! =TL
SQL Server #$$% supports nontraditional data &"eb Services! 7ML' out
of the box! in the following ways-
8
SSIS brings analytics to the data without persisting the data.
8
4ata mining and text mining can be done in the data *ow.
8
4ata mining and analytics are brought to the data *ow for data
5uality and data cleansing.
4na!ysis Services
"ith SQL Server #$$%! Analysis Services provides! for the )rst time! a
uni)ed and integrated view of all your business data as the foundation
for your traditional reporting! online analytical processing &.LAD'
analysis! and data mining.
0nified Di-ensiona! :ode!
Iy combining the best aspects of traditional .LAD analysis and
relational reporting! Analysis Services provides a metadata model that
covers both sets of needs. A set of cubes and dimensions de)ned in
Analysis Services is referred to as a >ni)ed 4imensional Model &>4M'.
The >4M is a central metadata repository de)ning business entities!
business logic! calculations! and metrics that serves as the source for
Visit: www.gcreddy.net for Testing Information
130
Visit: www.gcreddy.com for QTP Information
all reports! spreadsheets! .LAD browsers! HDIs! and analytical
applications.
>sing the powerful new 4ata Source 0iew feature! the >4M is mapped
to a host of heterogeneous bac+6end data sources! providing a
complete and integrated picture of the business regardless of the
location of the data.
"ith the >4Ms friendly descriptions of the business entities!
navigation hierarchies! multiple perspectives! and even automatic
translations to native languages! users will )nd it easy to explore the
corporate business data.
Data :ining
SQL Server #$$% 4ata Mining is the II technology that helps you build
complex analytical models! and integrate those models with your
business operations. Analysis Services establishes new ground for data
mining. Iy creating an easy6to6use! extensible! accessible! and *exible
platform! Analysis Services data mining capabilities introduce data
mining to organi(ations that previously would never have considered a
data mining solution.
Through an enterprise6class architecture! a deep integration with the
SQL Server family of II tools! and a rich set of other tools! ADIs! and
algorithms! SQL Server enables the creation of a new breed of
intelligent applications that enhance productivity! increase pro)ts! and
reduce costs by providing customi(ed data6driven solutions to a broad
range of business problems.
5e/orting Services
1eporting Services extends the Microsoft II platform to reach the
information wor+er who needs access to business data. 1eporting
Services is a server6based enterprise reporting environment! managed
through "eb services. 1eports can be delivered in a variety of formats!
with a range of interactivity and printing options. =omplex analyses
can reach a broad audience through the distribution of reports as a
data source for downstream II.
As an integrated component of SQL Server #$$%! 1eporting Services
provides the following-
8
A high6performance engine for processing and formatting reports.
Visit: www.gcreddy.net for Testing Information
131
Visit: www.gcreddy.com for QTP Information
8
A complete set of tools for creating! managing! and viewing reports.
8
An extensible architecture and open interfaces for embedding reports
or integrating reporting solutions in diverse IT environments.
5e!ationa! and 6L4> 5e/orts
1eports built on relational data are useful but the ability to add
additional analytic capabilities ma+es such reporting powerful.
1eporting Services allows you to easily build reports together or
separately. SQL Server #$$% supports both relational and .LAD data
and provides a 5uery editor for both! including SQL Query 3ditor and
M47 Query 3ditor.
5e/ort &ui!der
1eport Iuilder! a new component of SQL Server #$$% 1eporting
Services! allows business users to create their own reports using a
user6friendly model of their data. 1eport Iuilder ta+es advantage of the
1eporting Services platform to bring ad hoc reporting to all end users.
>sers create and edit reports with the 1eport Iuilder client application.
The 1eport Iuilder user interface is built on top of familiar Microsoft
.Lce paradigms such as Microsoft 3xcel and Microsoft DowerDoint.
:igure @ shows a sample 1eport Iuilder report.
Visit: www.gcreddy.net for Testing Information
132
Visit: www.gcreddy.com for QTP Information
Figure +9 Design 5e/orts wit8 5e/ort &ui!der
1eport Iuilder is a =lic+.nce application deployed through the
browser. >sers start by selecting report layout templates containing
prede)ned data sections such as tables! matrices! and charts. They
drag and drop report items from the model to the design surface and
set constraints to )lter the report data. The model contains all of the
necessary information for the 1eport Iuilder to automatically generate
the source 5uery and retrieve the re5uested data. The 1eport Iuilder
also allows users to-
8
Add text and formatting to reports.
8
=reate new )elds and calculations de)ned using the
model.
8
Dreview! print! and publish reports.
8
3xport report data to formats such as Microsoft
3xcel.
Integration wit8 t8e :icrosoft 6ffice Syste-
1eports served up by the 1eport Server in 1eporting Services can run
in the context of Microsoft ShareDoint Dortal Server and Microsoft .Lce
Visit: www.gcreddy.net for Testing Information
133
Visit: www.gcreddy.com for QTP Information
System applications such as Microsoft "ord and Microsoft 3xcel. ;ou
can use ShareDoint features to subscribe to reports! create new
versions of reports! and distribute reports. ;ou can also open reports in
"ord or 3xcel to view BTML versions of the reports.
0/grading to SQL Server 200)
The following are some tips for upgrading to SQL Server #$$%-
8
>pgrade to SQL Server #$$% from SQL Server 8.$ or SQL Server
#$$$.
8
1un >pgrade Advisor before upgrading to determine if any product
changes are expected to brea+ existing applications.
8
The SQL Server 4atabase 3ngine! Analysis Services! and 1eporting
Services can be upgraded by the setup program.
8
SQL Server Integration Services! the replacement for 4ata
Transformation Services &4TS'! is installed side by side with 4TS. ;ou
can run 4TS pac+ages using the 4TS runtime components.
8
SQL Server #$$% 2oti)cation Services is installed side by side with
2oti)cation Services #.$. ;ou must migrate instances of 2oti)cation
Services to SQL Server #$$% when you upgrade the SQL Server
4atabase 3ngine.
8
>se the Surface Area =on)guration tool after upgrading to enable or
disable SQL Server #$$% services! networ+ protocols! and features.
Visit: www.gcreddy.net for Testing Information
134
Visit: www.gcreddy.com for QTP Information
Visit: www.gcreddy.net for Testing Information
135

You might also like