Tải bản đầy đủ (.pdf) (50 trang)

Tài liệu Programming Microsoft SQL Server 2000 with Microsoft Visual Basic .Net - P2 pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (963.8 KB, 50 trang )

inform ation about views as well as tables. Specify a
TABLE_TYPE colum n value of VI EW in the WHERE clause for
a SELECT st at em ent t o return only views.
Wit h t he COLUMNS view of t he I NFORMATI ON_SCHEMA, you can ret urn
inform at ion about colum ns in a dat abase. The t hird bat ch illust rat es t his app-
lication. I t also r eveals a new sy nt ax for specifying t he database serving as the
source for t he view. Not ice t hat t he specificat ion of t he view nam e has t hr ee
parts. The first of t hese is t he dat abase nam e— Chapt er02. Designat ing a
database nam e as t he first part rem ov es t he need to designat e a dat abase
cont ext w it h a USE st at em ent . This is because no m at ter what dat abase cont ext
the st at em ent execut es, it always ext ract s infor m at ion from t he dat abase— that
is, the first part of t he I NFORMATI ON_SCHEMA view nam e. The second and t hird
part s follow t he convent ion for t he preceding bat ches except for t he nam e of t he
specific I NFORMATI ON_SCHEMA view ( COLUMNS) . The sam ple also includes a
WHERE clause t o reference a part icular table— in particu lar, Em ailCont act s.
Wit hout t he WHERE clause, t he T- SQL st at em ent in the bat ch will ret urn
inform at ion for all t he colum ns w it hin t he Chapt er02 dat abase, including t hose
from sy st em and user- defined t ables.
The final bat ch shows t he I NFORMATI ON_SCHEMA syntax for r eporting about t he
keys in a dat abase. These include t he prim ar y k eys, for eign k eys, and unique
keys. The inform at ion is really about t he colum ns on w hich an applicat ion defines
it s keys. As w it h t he pr eceding bat ch, t his sam ple restrict s t he result only t o keys
for t he Em ailContact s table.
--INFORMATION_SCHEMA_Samples
--List databases on current server.
USE master
SELECT * FROM INFORMATION_SCHEMA.SCHEMATA
GO

--List user-defined tables in Chapter02 database.
USE Chapter02


SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE NOT(SUBSTRING(TABLE_NAME,1,3) = ’sys’
OR SUBSTRING(TABLE_NAME,1,3) = ’dtp’)
GO

--List all columns in EmailContacts table.
SELECT * FROM Chapter02.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ’EmailContacts’
GO

--List data on columns constrained as keys in
--the EmailContacts table.
SELECT * FROM Chapter02.INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME = ’EmailContacts’
GO

Figure 2- 2 displays an excerpt from t he result set for t he preceding script . The
ret ur n for each batch begins w it h a new set of colum n headers. The list of
databases includes our user- defined database, Chapt er02, along wit h t he two SQL
Ser ver sam ple databases, pubs and Nort hwind, as well as t he four syst em
databases. The second header shows j ust one row for t he lone table in
Chapt er02. The t hird header rows reveal t he nam es of the four colum ns wit hin
the Em ailCont act s t able. This view provides m uch addit ional inform at ion about
each colum n, such as it s nullabilit y, dat a t ype, and relat ed settings, including it s
precision and scale if appropriat e. The row for t he last set of colum n headers
provides inform at ion about t he lone key for t he Em ailCont act s t able. This is t he
t able’s pr im ary key . Each key has a nam e, w hich appears in t he
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CONSTRAI NT_ NAME colum n. Because our synt ax for t he creat ion of t he t able
didn’t specify a nam e for t he pr im ary key, t he last row of out put in Fig ure 2-2

shows t he syst em -generat ed nam e for t he table’s prim ary key in t he
CONSTRAI NT_ NAME colum n. A subsequent sam ple in t he “ Script ing Keys and
I ndexes” sect ion illust rat es t he sy nt ax for assigning a specific nam e to a prim ary
key.
Figure 2 - 2 . Sa m ple out pu t from a se t of four T- SQL ba tche s illust r at in g
t he b eh avior of I NFORM ATI ON _ SCH EM A view s.

I NFORMATI ON_ SCHEMA offers m any m ore v iews besides those illust rat ed in t he
preceding four bat ches. For exam ple, you can gat her inform at ion about check
const raint s for colum n values, t able const raints, st ored procedures, and user-
defined funct ions. Refer t o t he “I nform at ion Schem a View” t opic in Books Online
for an overv iew of t he I NFORMATI ON_SCHEMA views along wit h links defining t he
result set for each t ype of view available.
W ork ing w it h Colum n Da t a Type s
The “Creat ing a Table” sect ion int roduced t he CREATE TABLE st at em ent sy nt ax
and dem onst rated how t o declar e t ypical sy st em dat a t ypes such as int and
nvarchar. Apply ing this fram ework w ill enable you to assign t he ot her dat a types
to colum ns as well. I n spit e of t he sim plicit y of t he ov erall approach, t here are
special issu es for som e data t ypes, and one dat a t ype hasn ’t been covered yet .
This sect ion r eviews t hese issu es.
Com p aring t im e st am p an d da tet im e Dat a Types
Those w ho are m igrat ing t o SQL Server m ay be confused at first by t he tim e-
st am p dat a t ype and w het her it has anyt hing t o do w it h datet im e dat a ( it
doesn’t ). The rowversion alias for t im est am p act ually sum m arizes the purpose of
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
the t im est am p dat a t ype m ore precisely. This m ay be one reason why Micr osoft
plans to use t he rowv ersion nam e m ore prom inent ly in t he fut ure.
The following script cont rast s t he t im est am p and dat et im e dat a t ypes. The
cont rast relies on t wo t ables, t 1 and t 2, each w it h t hree colum ns, col1, col2, and
col3. The col1 colum n has an int dat a t ype and offers a value for

program m at ically populat ing rows in each t able. The col2 and col3 colum ns
populat e aut om at ically . The data t ype for col2 is dat et im e, but it has a DEFAULT
const raint t hat assigns the current t im e aut om atically. Users and your
applicat ion’s code can override t his default value. The t im est am p dat a t ype also
autom at ically populates col3 in bot h t ables. However, for t his dat a t ype, only SQL
Ser ver updates the value. This occurs wit h t he insert ion of a new row or t he
revision of any value in an exist ing row.
Aft er cr eat ing t he t1 and t 2 t ables, t he scr ipt does a couple of operations t o
cont rast t im est am p and dat etim e dat a t ypes. The script insert s a record into each
table w it h a delay of 1 second bet ween each insert ion. The WAI TFOR DELAY
st at em ent act ually suspends t he operat ion of SQL Server for t he durat ion of it s
argum ent . Therefore, t he insert ion for t able t2 can occur m ore t han 1 second
aft er the insert ion for t able t 1 because SQL Server requires t im e t o perfor m the
operat ion. After running a SELECT query t o show the colum n values in t ables t 1
and t 2, t he script next updat es t he value of col1 in t able t 2. Then it reruns t he
SELECT quer y t o dem onst rate t he im pact of t he operat ion on the colum n values
in t he sam ple. At t he sam ple’s conclusion, the scr ipt rem oves t he t1 and t 2 tables
from t he Chapt er02 dat abase.
--CompareTimestampToDatetime
--Execute statements after USE from Chapter02 database.
USE Chapter02

--Create two tables named t1 and t2.
CREATE TABLE t1
(
col1 int,
col2 datetime DEFAULT GETDATE(),
col3 timestamp
)
CREATE TABLE t2

(
col1 int,
col2 datetime DEFAULT GETDATE(),
col3 timestamp
)
GO

--Insert a row in tables t1 and t2 with
--a one-second delay between tables.
INSERT INTO t1 (col1) VALUES (1)
WAITFOR DELAY ’00:00:01’
INSERT INTO t2 (col1) VALUES (1)
GO

--Run queries on tables t1 and t2.
SELECT ’t1’ AS ’Table Name’, * FROM t1
SELECT ’t2’ AS ’Table Name’, * FROM t2
GO

--Update column col1 in table t2.
UPDATE t2 SET col1 = col1 + 2
GO

--Re-run queries on tables t1 and t2.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
SELECT ’t1’ AS ’Table Name’, * FROM t1
SELECT ’t2’ AS ’Table Name’, * FROM t2
GO

--Drop tables t1 and t2.

DROP TABLE t1
DROP TABLE t2
GO

Figure 2- 3 sh ows the Result s pane from Query Analyzer for t he preceding script.
The col2 value for t he second row is 1 second plus a SQL Server clock t ick (3
m illiseconds) behind t he col2 value for t he first row. This clock t ick is the t im e
that it takes t o com plet e t he row insert ion for t able t2. The col3 values for t he
first and second rows are displaced by 1. Because the insert ion for t able t 2
occurred im m ediat ely aft er t he one for table t 1, t his is appropriat e. I f other
insert ions t ook place bet ween t he init ial insert ion for table t1 and table t 2, the
difference in t he binary value for col3 w ould be great er. Th e updat e of col1 for
table t 2 dem onst rat es t his point .
The second pair of rows in Fig ure 2- 3 also displays t he colum n values for tables
t1 and t 2 after an updat e t o col1 in t able t 2. I n the case of t able t 1, t he col3
value rem ains unalt ered. However, t he col3 value for t able t2 grows by 1 from it s
init ial value aft er t he insert ion. This incr eased value reflect s t he im pact of t he
updat e to col1 in t able t 2. While t he second pair of rows varies from t he first pair
for col3 in Figure 2- 3, t he col2 values are ident ical between t he first and second
pair of rows. This is because updat ing values of ot her colum ns has no im pact on
the dat et im e values in col2, but updating any value in a row does im pact t he
value of t he t im est am p colum n value in t he row.
N ot e
You can have just one colum n per table with a t im est am p
dat a t ype.
Figure 2 - 3 . Sam ple out pu t contr ast ing t he beh avior of da tet im e an d
t im e st am p da ta t ypes.

Usin g sql_ v ariant D at a Typ e V alue s
The sql_v ariant dat a type is the only dat a t ype t hat let s you st ore different data

types in t he sam e colum n. This capability is useful for st oring a collect ion of
values in a colum n in which you don’t know in advance what types of values you’ll
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
have. This can arise in a sit uat ion in which you let a user define values on an ad
hoc basis.
Consider a t able t hat st or es m iscellaneous inform at ion about cont act s. Som et im e
your applicat ion m ay need t o st ore a m oney dat a t ype, anot her t im e a user m ay
want t o specify a dat e, and in yet ot her cases, your application m ay need t o
designat e a variable- lengt h charact er value. This kind of scenar io is t ypical of
sit uat ions in which your application needs to charact erize elem ent s but t he
com plet e set of elem ent s and their at t ribut es isn’t known at t he t im e t hat you
develop t he applicat ion.
The follow ing script assigns a set of ext ended propert ies t o a t able of cont act s
ident ified by a Cont actI D colum n. Not ice t hat t he CREATE TABLE st at em ent uses
t hr ee colum ns t o charact erize t he cont act s. The m ost im port ant colum n is
PropValue, w hich has a sql_variant dat a t ype. This colum n st ores t he act ual value
t hat charact erizes a cont act . I n som e cases, t he cont act charact er ist ic is a
m onet ary value, in ot her cases it is a dat e, and in st ill ot her cases it is a st ring
value, such as t he nam e of a favorit e sport or st ore. PropI D and PropNam e
describe t he charact erist ic for t he cont act . PropNam e m ak es it easy t o follow
what t he PropValue colum n values describe wit hout r equiring anot her t able t o
decode t he PropI D colum n values. A subsequent sam ple w ill ret urn t o t he
Cont act ExtProps table and link it t o ot her tables cont aining cont act and propert y
nam es. I n addit ion, t hat sam ple w ill add a prim ary key t o t he t able. These
refinem ent s aren’t necessary t o dem onst rat e t he behavior of sql_variant dat a
t ypes.
The I NSERT I NTO st at em ent s t hat add values to t he Pr opValue colum n use CAST
funct ions to est ablish sub dat a t ypes w it hin t he sql_variant colum n. This isn’t
st rict ly necessary, but t he CAST funct ion confir m s t he abilit y of t he sql_variant
dat a t ype t o accept m ult iple ot her dat a t ypes.

--SQL_variantSample
--Execute statements after USE from Chapter02 database.
USE Chapter02
GO

--Remove prior version of ContactExtProps if it exists.
IF EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = ’ContactExtProps’
)
DROP TABLE ContactExtProps
GO

--Create ContactExtProps with four columns.
CREATE TABLE ContactExtProps
(
ContactID int NOT NULL,
PropID int NOT NULL,
PropName nvarchar(20),
PropValue sql_variant
)
GO

--Populate ContactExtProps with values.
INSERT INTO ContactExtProps
VALUES(1, 1,’Birthday’, CAST(‘9/9/1944’ AS datetime))
INSERT INTO ContactExtProps
VALUES(1, 2, ’Salary’, CAST(50000 AS money))

INSERT INTO ContactExtProps
VALUES(1, 3, ’Bonus’, CAST(30000 AS money))
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
INSERT INTO ContactExtProps
VALUES(1, 4, ’Favorite Sport’, ’Boxing’)
INSERT INTO ContactExtProps
VALUES(2, 1, ’Birthday’, CAST(‘1/1/1950’ AS datetime))
INSERT INTO ContactExtProps
VALUES(2, 2, ’Salary’, CAST(60000 AS money))
INSERT INTO ContactExtProps
VALUES(2, 3, ’Bonus’, CAST(40000 AS money))
INSERT INTO ContactExtProps
VALUES(2, 5, ’Favorite Store’, CAST(‘Tailspin Toys’ AS nvarchar(2
0)))
GO

--Select all records with a Favorite Store property.
SELECT ContactID, PropName, PropValue
FROM ContactExtProps
WHERE PropName = ’Favorite Store’
GO

--Select Salary and Bonus properties and add one to
--money data type for Salary and Bonus properties.
SELECT ContactID, PropName, Cast(PropValue AS money)+1, PropValue
FROM ContactExtProps
WHERE PropID >=2 and PropID <=3
GO

--This SELECT fails because sql_variant doesn’t implicitly

--convert to other data types (for example, money)
SELECT ContactID, PropName, Cast(PropValue AS money), PropValue+1
FROM ContactExtProps
WHERE PropID >=2 and PropID <=3
GO

Three SELECT queries at t he end of t he preceding script illust rat e som e of your
options for extract ing dat a from colum ns declared w it h a sql_var iant data t ype.
The first SELECT query includes PropValue, t he sql_var iant dat a t ype, in t he
SELECT list for a query , but it uses a colum n defined wit h t he nvarchar dat a t ype
in a WHERE clause. This SELECT query succeeds and ret urns t he nam e of t he
favorite st ore for any record t hat has the PropNam e value ’Favorite St ore’.
The second SELECT query uses PropI D, a colum n wit h an int data t ype, in t he
WHERE clause t o extract records with inform ation about salary and bonus for
cont act s in the PropValue colum n. Th is sam ple t ransf orm s t he sql_variant dat a
type for PropValue t o a m oney dat a t ype in the SELECT list . Then it adds 1 t o t he
transform ed value. This addit ion operat ion succeeds because it works wit h t he
explicit ly convert ed sql_var iant data t ype.
The last SELECT query tries t he sam e addit ion t ask as t he second SELECT query,
but its SELECT list relies on an im plicit t ransform at ion of t he sql_variant dat a t ype
to a dat a type t hat support s addit ion. Because SQL Server doesn’t support t his
transform at ion for a sql_var iant source dat a t ype, t he last SELECT query fails.
Figure 2- 4 displays t he out put from t he first two successful query st at em ent s.
Figure 2 - 4 . Not ice t ha t t h e Pr opVa lu e colum n, w hich h as a sql_ va rian t
data t ype, r et u rns values w it h diffe re nt data t ype form at s, su ch a s
va ria ble-lengt h cha ra ct er st rin gs and m one y.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Usin g Com pu te d Colum n s in Table s
A com put ed colum n adds a virt ual colum n t o a t able based on an expression t hat

draws on one or m ore other colum ns wit hin the table. You can specify a
com puted colum n wit h a CREATE TABLE (or an ALTER TABLE) st at em ent . You can
use a com put ed colum n in a SELECT list , a WHERE clause, or an ORDER BY
clause. I n addition, com puted colum ns can part icipat e in t he definition of an index
or prim ary key. You can also use a com put ed colum n in t he definit ion of a
UNI QUE const raint. When you’re using a com put ed colum n t o help define a
prim ary key or an index, t he expression m ust be det erm inist ic. I n ot her words,
the expression m ust generat e t he sam e result all t he tim e based on t he sam e
input . An expression based on GETDATE isn’t appropriat e for a com put ed colum n
that will serve as a colum n for an index. This is because t he result will change
each t im e you open t he t able.
Despit e the wide range of uses for com put ed colum ns, t here are sev eral
circum st ances in which you cannot use t hem . For exam ple, you cannot sp ecify
nullabilit y for com put ed colum ns. This is because SQL Ser ver autom at ically
det erm ines w het her a com put ed colum n is null based on it s input and t he
expression for com bining t he com put ed colum ns in quest ion. Even non- nullable
input s can generat e null r esult s if an expression generat es an underflow or
ov erflow. I n addition, you cannot specify input s or m odify t he cont ent s of
colum ns w it h I NSERT I NTO or UPDATE st at em ents. Yet another applicat ion t hat
doesn’t perm it t he use of com put ed colum ns is that which defines FOREI GN KEY
and DEFAULT const raint s.
The follow ing script sam ple illust rat es t he sy ntax for sp ecifying a com put ed
colum n and shows an exam ple of how t o use it . The CREATE TABLE st at em ent
designat es t hr ee colum ns for t he Proj ect edDeliveryDat es table. The first colum n is
autoincr em ent ing, wit h default set tings for t he I DENTI TY colum n pr oper ty. The
second colum n has a dat et im e dat a t ype for accept ing order dat es. The third
colum n is a com put ed colum n. The expression for t he colum n uses the Dat eAdd
funct ion to com pute a proj ect ed delivery dat e based on t he t able’s OrderDat e
colum n.
N ot e

The I DENTI TY property perm its y ou to set t he seed value
and t he st ep value for an aut oincrem enting series. I t s default
seed and st ep values are both 1. You can specify alternat e
seed and st ep values by adding parentheses aft er the
keyword. For exam ple, use I DENTI TY(100, 10) t o specify a
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
series that st art s at 100 and progresses in steps of 10.
--ComputedColumnSample
--Execute statements after USE from Chapter02 database.
USE Chapter02
GO

--Remove prior version of ProjectedDeliveryDates if it exists.
IF EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = ’ProjectedDeliveryDates’
)
DROP TABLE ProjectedDeliveryDates

--Create ProjectedDeliveryDates with three columns.
CREATE TABLE ProjectedDeliveryDates
(
OrderID int IDENTITY Not Null PRIMARY KEY,
OrderDate datetime Not Null,
ProjectedDeliveryDate AS DateAdd(day, 10, OrderDate)
)
GO


--Populate ProjectedDeliveryDates.
INSERT INTO ProjectedDeliveryDates
Values(GetDate())
INSERT INTO ProjectedDeliveryDates
Values(‘9/1/01’)

--Display date and time for projected delivery.
SELECT OrderID, OrderDate, ProjectedDeliveryDate
FROM ProjectedDeliveryDates

--Display just date for projected delivery.
SELECT OrderID, OrderDate,
LEFT(ProjectedDeliveryDate,12)
AS ’ProjectedDeliveryDate’
FROM ProjectedDeliveryDates
GO

Aft er insert ing order dat es based on eit her t he GETDATE funct ion or a st ring
represent ing a dat e, t he script queries t he Proj ect edDeliveryDat es table wit h t wo
separat e SELECT queries. The first SELECT query st at em ent dem onst rat es t he
com puted colum n as part of t he list for t he st at em ent. For this st at em ent, t he
Proj ect edDeliveryDat e colum n displays bot h t he dat e and t he t im e. However,
your applicat ion m ay require j ust t he dat e. The second query stat em ent shows
how t o cr op t he t im e value out of t he display. Figure 2- 5 present s the output
from bot h SELECT st at em ent s.
Figure 2 - 5 . Th is exam ple sh ow s t he u se of a com pu t ed colu m n to disp la y
a pr oj ect e d d at e for t he de livery of an or de r in eit he r of t w o
re pre se nt at ions—on e t ha t inclu des a t im e a nd an ot h er t h at show s on ly a
date .
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.


Adding Check Con st raint s
Check const raints are am ong t he m ost sim ple of the const raint t ypes available t o
database dev elopers and adm inist rators. Basically, a ch eck const raint allows you
to r est rict the values entering a colum n— som ewhat in t he way t hat dat a type
specificat ions do. (Users cannot ent er a charact er st ring into a colum n wit h an int
data t ype.) However, check const raints base t heir rest rict ion on a Boolean
expression t hat evaluat es t o Tr ue or False. The const raint expression can draw on
one or m ore colum n values from t he t able to which it applies. A colum n const raint
applies to an individual colum n, and a table const raint references two or m or e
colum ns. The value False for t he expression violat es t he const raint . SQL Server
rej ect s the insert ion of a r ecord wit h a value t hat violat es a const raint . You can
use t his behavior t o m aint ain the int egrity of t he colum n values in t he t ables of
your dat abase applicat ions.
The follow ing script has three bat ches of st at em ent s. First the scr ipt adds a
colum n check const raint t o t he Em ailCont act s t able init ially generat ed in the
“Creating a Table” sect ion. The first bat ch also t est s the const raint by attem pt ing
to insert a row wit h a colum n value t hat v iolat es t he const raint . I n t he second
batch, the scr ipt shows how t o disable a const raint. Th is bat ch at t em pt s t o insert
the sam e record t hat failed in t he first bat ch, but t his tim e t he insertion succeeds.
The t hird bat ch dr ops t he const raint from t he Em ailCont acts t able and delet es t he
record added in t he second bat ch.
You can use t he ALTER TABLE st at em ent t o add a colum n check const raint t o a
table, su ch as Em ailCont act s. The ALTER TABLE st at em ent perm it s the
m odificat ion of a t able after its creat ion. Besides adding ch eck const raint s, you
can add ot her const raint s, such as prim ary or for eign keys, and new colum ns. To
add a const raint , use t he ADD k eyword followed by CONSTRAI NT. You can
optionally assign a const raint nam e. Specifying a const raint nam e is par ticular ly
convenient if your applicat ion has a need t o disable or rem ov e a const raint . I f you
don’t explicit ly nam e your const raints, SQL Server aut om at ically assigns a nam e.

The CHECK keyword specifies t he t ype of const raint. Finally, t he expression
trailing t he CHECK keyw ord repr esents t he condit ion for which t he ch eck
const raint t est s. I n t he sam ple script , t he const raint evaluat es t he Email1 value
to ensure t hat it cont ains t he @ sy m bol. E-m ail addresses t hat don’t include t his
sym bol are invalid.
--ColumnCheckConstraintSample
USE Chapter02

--Add CHECK constraint to require at
--least one @ in Email1.
ALTER TABLE EmailContacts
ADD CONSTRAINT ch_EmailContacts_Email1_for@
CHECK (CHARINDEX(‘@’,Email1)<>0)

--Test constraint with an Email1 value
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
--that contains no @; the INSERT statement fails.
INSERT INTO EmailContacts
VALUES (3,’Karl’, ’Doe1’, ’Doe1.hlcofvirginia.com’)
GO

--Disable the constraint.
ALTER TABLE EmailContacts
NOCHECK CONSTRAINT ch_EmailContacts_Email1_for@

--Test the disabled constraint with an Email1 value
--that contains no @; the INSERT statement succeeds.
INSERT INTO EmailContacts
VALUES (3,’Karl’, ’Doe1’, ’Doe1.hlcofvirginia.com’)
GO


--Drop the constraint and delete bad Email1 row.
ALTER TABLE EmailContacts
DROP CONSTRAINT ch_EmailContacts_Email1_for@
DELETE FROM EmailContacts
WHERE LastName = ’Doe1’
GO

Scr ipt ing Keys and I n dex es
This sect ion drills down on techniques for script ing prim ary keys, for eign keys,
and indexes in your tables. Each t opic begins wit h a brief descr iption of
background issues befor e t he discussion of a sam ple or t wo t hat illust rate t ypical
uses for t he t opic.
Prim a ry Keys
Prim ar y keys have t wo especially dist inct ive feat ures. Fir st, each row m ust have a
unique prim ary key value. Second, no prim ary key value can be null— even if it is
the only null record in a t able. I t is com m on, but not m andat ory, t o base prim ary
keys on a single colum n wit h an I DENTI TY propert y setting. A prim ary key can
span m ult iple colum ns.
Each pr im ar y key cr eat es an index. An index is a dat abase obj ect t hat support s
fast access to the rows wit hin a t able or view. Any one SQL Serv er table can have
up t o 250 index es, but only one of t hese can be clust ered. A clust ered index
physically orders t he records for a t able in st orage according t o t he index values.
Because a clust ered index can speed perform ance so m uch, you sh ould reserv e
the clust ered index so t hat it serves your applicat ion’s m ost heav ily used lookup
requir em ent . You can m ake eit her t he index for t he prim ary key or anot her index
the clust ered index for a t able. Wit h a st andard SQL Server inst allat ion, a prim ary
key declarat ion m ak es t he prim ary key clust ered by default . However, you can
explicit ly declare a prim ary key as nonclust ered.
As m ent ioned previously, t he prim ary k ey can have it s nam e assigned eit her by

the sy st em or by a user . The follow ing script sam ple re-creat es t he Em ailCont act s
table. I f you check t he sam ple in t hat sect ion, you w ill observe t hat the prim ary
key declarat ion doesn’t include a nam e for t he prim ary key. The follow ing script
re- creat es t he generat ion of t he Em ailCont act s table, but t his sam ple does
explicit ly nam e t he prim ary key. The sam ple also dem onst rat es t he use of t he
sp_pkeys syst em st ored procedure— once before dropping t he first version of the
Em ailCont act s t able and a second t im e aft er creat ing a new version of the t able
wit h a user- defined nam e for t he prim ary key. The sp_pkeys syst em st ored
procedure has a result set w it h a separat e row for each colum n in t he prim ary
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
key. Th e colum ns of t he resu lt set report such it em s as t he dat abase nam e, t he
table nam e, and t he prim ary key nam e.
The prim ary key declaration in t his sect ion perform s ident ically to t he one in t he
“Creating a Table” sect ion ex cept for t he assignm ent of a nam e t o t he prim ary
key. I n t his inst ance, t he sam ple uses the CONSTRAI NT keyword. This is opt ional
for a prim ary key, but it s use can rem ind you t hat t he prim ary key is a m em ber
of t he fam ily of const raints, including check const raint s and foreign key
const raint s. Th e nam e for t he prim ary key appears im m ediat ely aft er t he
CONSTRAI NT keyword. The follow ing scr ipt also explicit ly declares t he prim ary
key as clust ered. You can replace t he k eyword CLUSTERED wit h NONCLUSTERED
to avoid physically ordering t he records in t he t able according t o Cont actI D
values.
--CreateEmailContactsTableWithPKName
--Execute statements after USE from Chapter02 database.
USE Chapter02
GO

--Print primary key columns and remove prior version
--of EmailContacts, if the table exists.
IF EXISTS

(
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = ’EmailContacts’
)
BEGIN
EXEC sp_pkeys ’EmailContacts’
DROP TABLE EmailContacts
END

--Create EmailContacts with three columns while
--explicitly assigning a name to the primary key.
CREATE TABLE EmailContacts
(
ContactID int Not Null
CONSTRAINT pk_EmailContacts_ContactID PRIMARY KEY CLUSTERED,
FirstName nvarchar(20),
LastName nvarchar(35),
Email1 nvarchar (255)
)
GO

--Populate EmailContacts and run a SELECT query
INSERT INTO EmailContacts
VALUES(1,’Rick’, ’Dobson’, ’’)
INSERT INTO EmailContacts
VALUES(2,’Virginia’, ’Dobson’, ’’)
SELECT * FROM EmailContacts
GO


--List primary key columns in EmailContacts.
EXEC sp_pkeys ’EmailContacts’

Figure 2- 6 sh ows the out put from t he preceding script . Th e results below the first
and t hird colum n headers reveal t he output from t he sp_pkeys syst em st ored
procedure before and after t he nam ing of t he prim ary key . The first set of colum n
headers shows the system defined nam e for t he prim ary key. The t hird set of
colum n headers shows t he out put from t he sp _keys st ored pr ocedure after t he
assignm ent of a nam e t o the prim ary k ey. Not ice how t he PK_NAME colum n value
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
in t he last row of Figure 2-6 m at ches t he nam e assigned t o t he prim ary key in the
preceding scr ipt .
Figure 2 - 6 . Sa m ple out pu t de m on st ra t ing pr im ary key nam es a ssign ed by
the syste m ( t op r ow ) a nd by the pr ece ding scr ip t ( bot t om r ow ) .

Recall t hat t he “Using sql_var iant Dat a Ty pe Values” sect ion init ially creat ed t he
Cont act ExtProps table. When it was creat ed in t hat sect ion, t he script didn’t
creat e a pr im ary key for it. I n addit ion, t he Cont act Ext Props t able includes a
colum n, PropI D, designed t o link to anot her t able t hat defines nam es t o m at ch
the PropI D values. The next scr ipt cr eat es a table, ExtProps, t hat m at ches t he
PropI D int values with nam es in a colum n of variable- lengt h charact er st rings.
The script t hen proceeds to use t he sp_pkeys syst em st or ed pr ocedure t o
det erm ine w het her a prim ary key colum n is already in t he Cont act ExtProps t able.
A value of 0 for @@ROWCOUNT specifies no prim ary key. I f t he value is greater
than 0, t he procedure drops the ex ist ing pr im ary k ey. Next t he procedure uses an
ALTER TABLE st atem ent t o creat e a new pr im ary key based on t wo colum ns—
Cont act I D and PropI D. This prim ary key desi- gnat ion perm it s each cont act t o
have m ult iple propert ies but no m ore t han one setting for any one propert y. The
foreign key sam ple in t he next sect ion w ill dem onst rat e how t o link t he
Cont act ExtProps table t o the Em ailCont act s and Ext Pr ops t ables.

--CreateExtProps
--Execute statements after USE from Chapter02 database.
USE Chapter02
GO

--Remove prior version of ExtProps, if it exists.
IF EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = ’ExtProps’
)
DROP TABLE ExtProps
GO

--Create ExtProps.
CREATE TABLE ExtProps
(
PropID int,
PropName nvarchar(20),
)

--Populate ExtProps with values.
INSERT INTO ExtProps
VALUES(1, ’Birthday’)
INSERT INTO ExtProps
VALUES(2, ’Salary’)
INSERT INTO ExtProps
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
VALUES(3, ’Bonus’)

INSERT INTO ExtProps
VALUES(4, ’Favorite Sport’)
INSERT INTO ExtProps
VALUES(5, ’Favorite Store’)
GO

--Drop primary key for ContactExtProps.
EXEC sp_pkeys ContactExtProps, dbo, Chapter02
IF @@ROWCOUNT > 0
ALTER TABLE ContactExtProps
DROP CONSTRAINT pk_ContactExtProps_ContactID_PropID
GO

--Add Primary Key based on ContactID and PropID.
ALTER TABLE ContactExtProps
ADD CONSTRAINT pk_ContactExtProps_ContactID_PropID
PRIMARY KEY NONCLUSTERED
(
ContactID,
PropID
)

--List primary key columns in ContactExtProps.
EXEC sp_pkeys ’ContactExtProps’

The preceding scr ipt closes by invoking t he sp_pkeys sy st em st ored procedure.
The out put from t he procedure appears in Figure 2- 7. Not ice t hat it cont ains t wo
rows— one for each colum n t hat cont ribut es t o t he prim ary key for t he
Cont act ExtProps table.
Figure 2 - 7 . Ou t put from t he sp_ pkeys syst em stored procedur e th a t

sh ow s a pr im a ry k ey defined on t w o colu m ns.

Fore ign Keys
Foreign keys are colum n values in one table t hat point t o t he prim ary k ey or
unique k ey in anot her t able. Specifying a foreign key enforces referent ial int egrit y
bet ween t he t wo t ables. Referential int egrit y r equir es all new records added t o
the t able wit h t he for eign key to m at ch eit her a prim ary or a unique key value in
the ot her table if it isn’t null. You can opt ionally specify act ions t o occur when you
updat e or rem ove a prim ary or unique key in t he t able on t he ot her end of t he
foreign key relat ionsh ip. Specifically, you can cascade t he change from t he t able
wit h t he prim ary or unique key t o t he one w it h t he foreign key. Alt ernat ively, you
can choose no act ion t o occur in t he table wit h t he foreign k ey as a consequence
of updat es t o t he t able wit h t he prim ary or unique key.
The follow ing script adds a couple of foreign k eys to the Cont act Ext Props t able.
The first foreign key uses t he Cont act I D in t he Cont act Ext Props t able t o refer t o
the prim ary key for t he Em ailCont act s table. The second foreign k ey uses the
Cont act ExtProps table v ia its PropI D colum n values t o refer to the Ext Props t able.
Because t he Ext Props t able doesn’t init ially hav e a prim ary or a unique k ey, t he
table cannot part icipat e in a foreign key relat ionship. Ther efor e, t he script first
adds const raints t o t he PropI D colum n in ExtProps so t hat it serves as t he t able’s
prim ary key. Then it declares t he foreign key relat ionship bet ween t he
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Cont act ExtProps table and t he Ext Props table. Alt hough t he first foreign key
doesn’t declare any cascading act ion, t he declarat ion for t he second foreign key
specifies cascading updat es. The script sam ple illust rat es t he sy nt ax for
designat ing cascading updat es in it s declarat ion. Aft er t he second foreign k ey
declarat ion, t he scr ipt t est s t he cascading updat e behavior by m ak ing a change t o
a PropI D value in the Ext Props table and t hen v erifying t hat t he updat e cascades
t o t he corresp onding PropI D value in t he Cont act ExtProps t able. The scr ipt
sam ple concludes by rest oring t he values and t he dat abase design t o t heir form er

st at e befor e t he addit ion of eit her for eign k ey. This m akes it possible t o rerun t he
script w it hout any m anual set up act ivit y bet w een runs.
You add a foreign k ey t o a t able as a const raint . The synt ax for perform ing t his
t ask has at least t hree st eps, and it can have m ore if you specify a cascading
act ion. Begin t he foreign key declarat ion inside an ALTER TABLE st at em ent . Aft er
you open t he ALTER TABLE st at em ent , t he first st ep is to indicate t hat you want
t o add a const raint w it h t he ADD and CONSTRAI NT keywords. You can,
optionally, assign a nam e t o t he foreign key const raint . Next add t he FOREI GN
KEY keyword and follow it wit h parent heses cont aining t he nam es of t he colum ns
from t he cur rent t able part icipat ing in t he r elat ionship. Th ird add REFERENCES as
a keyword. Follow t his keyw ord w it h t he nam e of t he t able t o which the
relat ionsh ip refers. Then, in parent heses after t he t able nam e, add t he colum n
nam es from t hat t able t hat part icipat e in t he relat ionship. By default , updat e and
delet e act ions don’t cascade from t he t able wit h t he unique key or prim ary key t o
t he t able wit h t he for eign key. How ever, y ou can opt ionally add an ON UPDATE or
ON DELETE clause t o t he foreign key declarat ion. I nclude in eit her clause
CASCADE t o t ransfer t he act ion from t he t able wit h t he prim ary or unique key t o
t he one with t he foreign key.
--ForeignKeysSamples
--Beginning of first FOREIGN KEY sample.
USE Chapter02

--Remove FOREIGN KEY constraint if it exists already.
EXEC sp_fkeys @fktable_name = N’ContactExtProps’
IF @@ROWCOUNT > 0
BEGIN
ALTER TABLE ContactExtProps
DROP CONSTRAINT ContactExtProps_fkey_ContactID
END


--Then, add a new FOREIGN KEY constraint.
ALTER TABLE ContactExtProps
ADD CONSTRAINT ContactExtProps_fkey_ContactID
FOREIGN KEY (ContactID)
REFERENCES EmailContacts(ContactID)

--Verify addition of new constraint.
EXEC sp_fkeys @fktable_name = N’ContactExtProps’
--End of first FOREIGN KEY sample


--Beginning of second FOREIGN KEY sample.
--Convert PropID in ExtProps to NOT NULL.
ALTER TABLE ExtProps
ALTER COLUMN PropID int NOT NULL
GO

--Then, define a primary key on PropID.
ALTER TABLE ExtProps
ADD CONSTRAINT pk_PropID PRIMARY KEY CLUSTERED (PropID)
GO
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

ALTER TABLE ContactExtProps
ADD CONSTRAINT ContactExtProps_fkey_PropID
FOREIGN KEY (PropID)
REFERENCES ExtProps(PropID)
ON UPDATE CASCADE

--Verify addition of new constraint.

EXEC sp_fkeys @fktable_name = N’ContactExtProps’
GO

--List ExtProps and ContactExtProps rows before
--update to ExtProps.
SELECT * FROM ExtProps
SELECT * FROM ContactExtProps

--Then, make a change in ExtProps that
--cascades to ContactExtProps.
UPDATE ExtProps
SET PropID = 50 WHERE PropID = 5

--List ExtProps and ContactExtProps rows after
--update to ExtProps.
SELECT * FROM ExtProps
SELECT * FROM ContactExtProps
GO
--End of second FOREIGN KEY sample.

--Do cleanup chores.
--Start to restore by resetting PropID values.
UPDATE ExtProps
SET PropID = 5 WHERE PropID = 50

--Next, drop FOREIGN KEY constraints.
ALTER TABLE ContactExtProps
DROP CONSTRAINT ContactExtProps_fkey_ContactID

ALTER TABLE ContactExtProps

DROP CONSTRAINT ContactExtProps_fkey_PropID

--Then, drop PRIMARY KEY constraint first .
ALTER TABLE ExtProps
DROP CONSTRAINT pk_PropID

--Finally, restore NULL setting for column.
ALTER TABLE ExtProps
ALTER COLUMN PropID int NULL
GO
--End of restore from second FOREIGN KEY sample.

Figure 2- 8 sh ows two excerpt s from t he preceding script ’s output. The t op panel
shows t he ExtProps t able rows over t he Cont act ExtProps t able rows. This is
befor e an updat e of t he PropI D value 5 t o a new value of 50 in t he Ex tPr ops
t able. The bot t om panel show s t he sam e two t ables aft er t he updat e of t he value
in t he Ext Props table. Not ice t hat t he change t o t he Ext Props table cascades t o
t he Cont act Ext Props table.
Figure 2 - 8 . Th e top and bot t om pa ne ls sh ow t h e Ext Props t able over t he
Con t act Ex t Props t a ble b efore and aft er a ch an ge t o t h e Ex tPr ops t ab le.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

I nde x e s
Many dat abases can achieve perform ance gains t hrough t he addit ion of an index.
I ndexes are great at speeding lookups and sort s. On the ot her hand, t here are
tim es when t he ov erhead associated with m aint aining an index can slow an
application. This is part icularly t rue w hen one or m ore indexes over lap wit h a
clust ered prim ary key. Oft en developers and adm inist rat ors have to resort to
tim ing runs for typical t asks t o det erm ine t he best configurat ion of indexes for a
database application. Wit h t his in m ind, t he value of being able t o add and drop

indexes program m at ically is considerable as you perform your t im ing runs t o
discern t he opt im al index configurat ion.
The last script in this chapter illust rat es several t echniques for work ing w it h
indexes t hat you are likely t o find useful. The scr ipt begins by creat ing a user-
defined stored procedure, List UserDefinedI ndexes, t hat list s the indexes for user -
defined t ables in a dat abase. ( You’ll r ead m uch m ore about st or ed procedures in
Chapt er 4.) See Figure 2- 9 for sam ple out put . This procedure draws on bot h t he
sysobj ect s and sy sindexes tables— t wo sy st em catalog t ables. While you should
generally av oid m anipulat ing syst em tables, som e advanced developers find it
useful to do so. The Nam e colum n from t he sysobj ect s t able ( sysobj ect s. nam e)
ret ur ns the t able for an index, and t he Nam e colum n from t he sysindexes table
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
(sysindex es.nam e) is the nam e for a specific index in a table ( if t here is one) . The
indid colum n presents t he index ident ifier colum n values. An indid value of 1
indicates a clust ered index, such as one creat ed wit h t he CREATE I NDEX
st at em ent or one associat ed w it h a prim ary key. Values of indid bet ween 2 and
250 are for nonclust ered indexes. An indid value of 0 indicates t here is no
clust ered index for a table. The indid colum n value also conveys inform at ion
about t ables containing large dat a t ypes, such as t ext , ntext , and im age. See t he
“Table and I ndex Archit ect ur e” t opic in Books Online for additional det ail.
N ot e
I nstead of using the List UserDefinedI ndexes stored
procedure in t he script below, you can use t he sy st em st ored
procedure sp_helpindex to collect inform at ion about indexes.
This syst em st ored procedure works sim ilarly to sp_pkeys
and sp_fkeys, but it provides information for indexes.
However, List UserDefinedI ndexes gives you exposure t o
techniques for w orking wit h syst em catalog tables, which are
a rich source of cont ent about a database’s design.
You can add an index t o a table w it h t he CREATE I NDEX st at em ent . The list ing

below init ially dem onst rat es t he syntax for creat ing an index based on one
colum n. Follow CREATE I NDEX wit h t he nam e of your index. Then follow the
index nam e wit h an ON clause. I n the ON clause, include t he table nam e wit h t he
colum n or colum ns for t he index. Place t he colum n nam e in parent heses aft er t he
table’s nam e.
The sam ple illust rates t he applicat ion of t he CREATE I NDEX sy nt ax t wice. The first
use of t he st at em ent is for adding an index based on t he Last Nam e colum n in t he
Em ailCont act s t able. Th is exam ple dem onst rat es how t o use t he CREATE I NDEX
st at em ent as described in the preceding paragraph. A second application of t he
st at em ent shows how t o creat e a unique index based on two colum ns from t he
Cont act ExtProps table— nam ely, Cont act I D and PropI D. Th e synt ax for t his
exam ple uses t he UNI QUE keyw ord. This keyw ord is appropriat e for a t able wit h a
candidat e key because it specifies a second index t hat is unique for each record
besides t he prim ary key. I n ot her words, t he colum n( s) contributing t o a unique
index ar e candidat es for the pr im ary key. By default , t he CREATE I NDEX
st at em ent generates nonclust ered indexes. However , you can insert CLUSTERED
aft er eit her CREATE or UNI QUE ( if it is pr esent ) t o m ake a clust er ed index.
Use t he DROP I NDEX st at em ent t o rem ov e a user -defined index (for ex am ple,
one you cr eat e wit h t he CREATE I NDEX st at em ent ) . The sy nt ax for t he DROP
I NDEX st at em ent uses a t wo-part nam e t o designat e the index t o dr op. The first
part is t he t able nam e, and t he second part is the index nam e. A per iod delim it s
the t wo part s. Our st or ed procedure list s t he indexes for prim ary keys and
syst em - defined index es. You can delet e t he index for a prim ar y k ey by dropping
the key. I f t he SQL Serv er set t ings for a server perm it it , you can rem ove t he
index for a foreign key direct ly from t he sysindex es table. See t he “How t o set
the allow updat es opt ion ( Ent erprise Manager) ” and “Error 259” t opics in Books
Online for m ore det ail on direct ly m anipulat ing system cat alog t ables, such as
sysindexes.
--IndexSamples
USE Chapter02

--Create a stored procedure to list for user-defined
--tables object name from sysobjects, and name and
--indid from sysindexes.
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_NAME = ’ListUserDefinedIndexes’)
DROP PROCEDURE ListUserDefinedIndexes
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
GO
CREATE PROCEDURE ListUserDefinedIndexes
AS
SELECT sysobjects.id AS [sysobjects.id],
sysindexes.id AS [sysindexes.id],
sysobjects.name AS [sysobjects.name],
sysindexes.name AS [sysindexes.name], sysindexes.indid
FROM sysobjects INNER JOIN sysindexes
ON sysobjects.id = dbo.sysindexes.id
WHERE (LEFT(sysobjects.name, 3) <> ’sys’)
AND (sysobjects.name <> N’dtproperties’)
GO

--List indexes data.
EXEC ListUserDefinedIndexes

--Create an Index for LastName in EmailContacts.
CREATE INDEX ind_EmailContacts_LastName
ON EmailContacts(LastName)

--List indexes data.
EXEC ListUserDefinedIndexes


--Remove previously created index.
DROP INDEX EmailContacts.ind_EmailContacts_LastName

--Remove primary key for ContactExtProps based
--on ContactID and PropID.
EXEC sp_pkeys ContactExtProps, dbo, Chapter02
IF @@ROWCOUNT > 0
ALTER TABLE ContactExtProps
DROP CONSTRAINT pk_ContactExtProps_ContactID_PropID
GO

--List indexes data.
EXEC ListUserDefinedIndexes
GO

--Create an Index for LastName in EmailContacts.
CREATE UNIQUE INDEX ind_ContactExtProps_ContactID_PropID
ON ContactExtProps(ContactID, PropID)

--List indexes data.
EXEC ListUserDefinedIndexes
GO

--Attempt to enter a record with duplicate key values for
--ContactID and PropID.
INSERT INTO ContactExtProps Values (1, 1, ’Birthday’, ’9/9/1964’)
GO

--Remove previously created index.
DROP INDEX ContactExtProps.ind_ContactExtProps_ContactID_PropID


--List indexes data.
EXEC ListUserDefinedIndexes
GO

--Insert and then delete record with duplicate values for
--ContactID and PropID columns.
INSERT INTO ContactExtProps Values (1, 1, ’Birthday’, ’9/9/1964’)
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
DELETE FROM ContactExtProps WHERE PropValue = ’9/9/1964’
GO

Besides synt ax issues, t he preceding sam ple script illust rat es design issues for
wor king wit h indexes, such as t est ing t he behavior of a unique index. To isolat e
the effect of t he index, t he scr ipt drops a prim ary key t hat requires uniqueness on
the sam e t wo colum ns as the ind_Cont act ExtProps_Cont act I D_PropI D index. The
test for t he validit y of t his unique index is an at t em pt t o ent er a record wit h a
duplicat e key value. After failing, t he script drops t he unique index and confirm s
that you can add t he record if t he unique index isn’t present ; t he script closes by
rem oving t he t est recor d.
Figure 2- 9 sh ows an ex cerpt from t he beginning of t he script w it h t he output from
the first t wo uses of t he List UserDefinedI ndexes st ored procedure. The m ain point
to t ake away from t he out put is t hat t he first list ing of index es doesn’t include a
reference t o ind_EmailCont act s_Last Nam e, but t he second one does. I n bet ween
the t wo runs of t he List UserDefinedI ndexes st ored procedure, t he scr ipt invokes
the CREATE I NDEX st at em ent t o generat e t he index . The t wo result set s also
show t he indexes for clust ered and nonclust ered prim ary keys. For exam ple,
pk_Em ailCont act s_Cont act I D is a clust er ed prim ary key; not ice t hat it s indid
value is 1. The index for the nonclust ered pr im ary key,
pk_Contact ExtProps_Cont act I D_PropI D, has an indid value of 2. Finally, t he

_WA_Sys_PropI D_77BFCB91 index is for a foreign key fr om a preceding sam ple.
SQL Server didn’t rem ove t he index w hen t he script dropped t he key.
Figure 2 - 9 . The se t w o re sult set s iden tify t he addit ion of a n index,
ind_ Em a ilCont act s_ La st N am e, t o t he Em a ilCon t act s t a ble . By cont rast in g
t he fir st w it h t he se con d list in g, you can see t he e ffe ct of t he CREATE
I NDEX st a t em e nt for ind_ Em a ilCont act s_ La st N am e.




Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Cha pt er 3 . Program m ing Data Acce ss
w it h T- SQL
This chapt er present s T- SQL program m ing t ech niques for dat a access. You can
use t hese t ech niques in m any environm ents— in Query Analyzer, encapsu lat ed
wit hin views, in st ored procedures and user-defined funct ions— and in Visual Basic
.NET. When you finish working t hrough t his chapter, you sh ould possess a
foundat ion for extract ing precisely t he dat a you need from a SQL Server dat abase
for any application.
The obj ect ive of t his ch apt er is to dem y st ify T- SQL dat a access techniques so t hat
you can creat e T- SQL SELECT st at em ent s as easily as you used t o w rit e DAO and
ADO dat a access code. Alt hough t he chapt er assum es you’r e work ing in Query
Analyzer, the t echniques you learn w ill apply equally when you use T- SQL
st at em ent s in Visual Basic .NET.
The chapt er begins by int roducing t he SELECT st at em ent and describing how t o
filt er colum ns and rows from a row source, such as a t able. Next t he chapt er
focuses on t echniques for aggr egat ing dat a acr oss a whole row source as well as
specific groups w it hin t he row source. The chapt er explor es part icular t echniques
for m oney and dat et im e var iables, and t he dat et im e t opic gains a sect ion of it s
ow n. The concluding sect ion exam ines ways of com bining r ow sources wit h j oins

and subqueries. I f you hav e had difficult y underst anding j oins befor e, spend
som e t im e wit h t he scr ipt sam ples in the chapt er and t he accom panying
com m ent ary t o build your grasp of t his im port ant capabilit y.
N ot e
By the term row source, I refer t o a collect ion of rows from a
dat abase. Although this can be a t able, it can also be a view
based on one or m ore t ables. I n addit ion, a row source can
be t he result set generated by a st ored procedure or a t able-
valued user- defined funct ion.
The T- SQL sam ples for t his chapter are available in an .sql file on t he com panion
disk . You can use the script s as start ing point s for your own cust om
ext rapolat ions of t he t echniques. You can run all t he sam ples from Query
Analyzer if y ou have the Nort hwind and pubs dat abases inst alled on a SQL Ser ver
inst ance t o which you can connect .


I nt roduct ion to Da ta Access w it h T- SQL
Creat ing efficient , speedy, and flex ible dat a access solut ions for SQL Server dat a
will inev it ably involve program m ing T- SQL. I n part icular, you will r equire a firm
foundat ion in t he design of SELECT st at em ent s. This sect ion int roduces t he
SELECT st at em ent by reviewing it s archit ect ure. You’ll find code sam ples
designed t o illust rat e t he basic operat ion of t he st at em ent ’s m ain elem ent s,
including t he SELECT list as well as t he FROM and WHERE clauses, and you’ll be
int roduced to t he t opic of calculat ed colum ns.
Ov erview of t he SELECT St a t em ent
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

×