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

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

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 (1.41 MB, 50 trang )

a disabled t rigger, all y ou have t o do is enable it . Recall t hat you can disable and
enable a t r igger w it h an ALTER TABLE st at em ent for the t able wit h t he t rigger
that you w ant to disable t em porarily.
The follow ing script dem onst rat es t he syntax for cr eat ing a trigger for t he
MyTable table cr eat ed earlier in t his chapt er. ( See t he “Creat ing a Scalar UDF
Wit hout Param et ers” sect ion.) The trigger prot ect s the table from insert s,
updat es, and delet es by rolling back t he t ransact ion associat ed w it h t he tr igger.
The script st art s by rem oving any previous version of t he
trgKeepMyTableUnt ouched tr igger and t hen begins a CREATE TRI GGER
st at em ent. Lik e m ost ot her CREATE st at em ents, t he CREATE TRI GGER st at em ent
m ust occur at the t op of a bat ch. Therefore, the code to drop the old version ends
wit h t he GO keyword. The ON clause of t he CREATE TRIGGER st at em ent
designat es the MyTable t able as the one t o w hich the t rigger will belong. The FOR
clause indicates t hat the t rigger will fir e for insert , updat e, and delet e ev ents.
The first st at em ent aft er t he AS keyword is a RAI SERROR st at em ent that sends a
cust om m essage back t o t he Messages pane of Query Analyzer. An inform at ional
m essage issued from a trigger is useful for let t ing a user k now t hat a t rigger
fired. The RAI SERROR st atem ent can serve ot her funct ions as well, but it is a
robust alt ernat iv e t o t he PRI NT st at em ent for sending m essages t o t he Messages
pane. The st ring for a cust om m essage can be up to 400 charact ers. The trailing
values 16 and 1 indicat e t he severity and st at e for t he err or. For sim ple
inform at ional m essages, you can consist ent ly apply these values. The second T-
SQL st at em ent in t he scr ipt rolls back t he t ransact ion to m odify the table. The
ROLLBACK TRAN st at em ent is an abbrev iat ed version of the ROLLBACK
TRANSACTI ON st at em ent. I n eit her form , t his st at em ent rem oves any insert ed
rows, rest ores any colum n values to t heir nonupdat ed st at e, and adds back any
delet ed r ows. You w ill generally want t o use t he ROLLBACK TRAN st at em ent as
the last st at em ent in a t rigger because any st at em ents after ROLLBACK TRAN can
m odify the t able for a t rigger.
--trgKeepMyTableUntouched
--Drop prior version of trigger.


IF EXISTS (SELECT name FROM sysobjects
WHERE name = ’trgKeepMyTableUntouched’ AND type = ’TR’)
DROP TRIGGER trgKeepMyTableUntouched
GO

--Create new trigger to keep MyTable table untouched.
CREATE TRIGGER trgKeepMyTableUntouched
ON MyTable
FOR INSERT, UPDATE, DELETE
AS
RAISERROR(‘Message from trgKeepMyTableUntouched.’,16,1)
ROLLBACK TRAN
GO

The follow ing script is a collect ion of T-SQL stat em ents t hat dem onst rat es t he
behavior of t he t rigger as well as how t o disable and rest ore the t r igger. The first
couple of bat ches in t he script at t em pt t o delet e all rows from t he MyTable table
and m odify a colum n value in t he table. Neither bat ch succeeds because t he
trgKeepMyTableUnt ouched tr igger prot ect s t he MyTable table fr om delet e and
updat e events (as well as insert events) .
I f it becom es essential t o m odify a t able wit h a trigger that blocks changes, y ou
can t em porar ily disable the t r igger. The script dem onst rates t he syntax for t he
trgKeepMyTableUnt ouched tr igger. You have to m odify the My Table table wit h t he
ALTER TABLE stat em ent to disable it s t rigger. After disabling t he trigger, the
script changes t he m axim um value in t he col1 colum n. Then, in anot her bat ch,
the script rest ores the init ial m ax im um value. The scripts use a scalar UDF
developed ear lier in t his chapter to accom plish t hese task s. After successfully
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
m odifying the t able wit h t he tr igger disabled, t he script enables t he t rigger again
for t he MyTable table with t he ALTER TABLE st atem ent . Just to confirm t he

trigger’s operat ion, the script again at t em pt s t o delet e all rows fr om t he t able.
The trigger fires and prints it s inform at ional m essage and rolls back the
transact ion t o rem ov e t he r ows from t he t able.
--Demo_trgKeepMyTableUntouched
--An attempt to delete all records fails with
--trigger error message.
DELETE
FROM MyTable
GO

--An attempt to update the maximum value in
--col1 in the MyTable table fails also.
UPDATE MyTable
SET col1 = dbo.udfOneHigherThanMax()
WHERE col1 = (SELECT MAX(col1) FROM MyTable)
GO

--Disable the trigger for MyTable without dropping it.
ALTER TABLE MyTable
Disable TRIGGER trgKeepMyTableUntouched
GO

--Update attempt for MyTable succeeds.
UPDATE MyTable
SET col1 = dbo.udfOneHigherThanMax()
WHERE col1 = (SELECT MAX(col1) FROM MyTable)

SELECT * FROM MyTable
GO


--Restoring update event also succeeds.
UPDATE MyTable
SET col1 = dbo.udfOneHigherThanMax() - 2
WHERE col1 = (SELECT MAX(col1) FROM MyTable)

SELECT * FROM MyTable
GO

--Re-enable trigger.
ALTER TABLE MyTable
Enable TRIGGER trgKeepMyTableUntouched
GO

--An attempt to delete all records fails again
--with trigger error message.
DELETE
FROM MyTable
GO

Ar chiving Changes t o a Table
The logical t ables insert ed and delet ed contain t he ch anges t hat users m ake t o a
table. Unfort unat ely, the insert ed and delet ed t ables are available only for t he
tim e that a t rigger has control of an applicat ion. When t he tr igger closes, SQL
Server in effect clears t he tables. I f you want t o persist som e su bset of t he
changes t o a t able for perm anent ready access, you can use triggers t o save the
cont ent s of the logical insert ed and delet ed t ables to a t able in a SQL Server
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
dat abase. Because changes ( insert s, updat es, and delet es) affect t he insert ed and
delet ed t ables differently, one approach is t o cr eat e a separat e t rigger for each
type of change. This sim plifies t he trigger logic, and it m akes each type of change

run fast er t han having one trigger t hat deciphers t he t ype of change and t hen
archives t he insert ed and delet ed t ables properly.
The follow ing script creat es three tr iggers to log insert s, updat es, and delet es to
the MyTable t able in the ChangeLogForMyTable table. The script st art s by
rem oving t he trgKeepMy TableUnt ouched t rigger creat ed in t he pr ev ious sam ple.
Recall that t he previous t rigger block s all changes t o t he MyTable t able. Next this
procedur e cr eat es a fresh blank version of the ChangeLogForMy Table table. The
table has four colum ns— one for t he col1 values from t he inserted or delet ed
t able, a second for t he t ype of change, a t hird for the dat e and tim e of the
change, and a fourt h colum n for t he login of the user m aking t he change.
Aft er cr eat ing a table t o arch iv e ch anges, the script creat es a fresh copy of the
trgI nsert ToChangeLog t rigger. This t r igger copies t he col1 value from t he inserted
t able to a local var iable. Then it uses the local variable in t he VALUES clause of an
I NSERT I NTO st at em ent to persist the new value to t he ChangeLogForMy Table
t able. The script uses a st ring const ant— I NSERT—t o designat e t he type of
change. The CURRENT_TI MESTAMP and SYSTEM_USER key words denot e built- in
funct ions that r et urn t he current dat e and t im e as w ell as the login for t he current
user (t he one who m ak es the change) .
The CREATE TRIGGER st at em ents for the t rgDelet eToChangeLog and
trgUpdat eToChangeLog triggers persist t he delet e and updat e col1 values t o t he
ChangeLogForMyTable table. When logging delet es, you use t he delet ed t able
inst ead of t he insert ed t able. I n t he case of updat es, you log t he cont ent s of t he
delet ed and insert ed t ables t o t he ChangeLogFor My Table table. However, the
basic design of delet e and updat e t riggers cor resp onds to t he
trgI nsert ToChangeLog trigger.
--trgInsertUpdateDeleteToChangeLog
--Drop prior version of trgKeepMyTableUntouched trigger.
IF EXISTS (SELECT name FROM sysobjects
WHERE name = ’trgKeepMyTableUntouched’ AND type = ’TR’)
DROP TRIGGER trgKeepMyTableUntouched

GO

--Remove prior version of ChangeLogForMyTable table.
IF EXISTS(SELECT TABLE_NAME = ’ChangeLogForMyTable’
FROM INFORMATION_SCHEMA.TABLES)
DROP TABLE ChangeLogForMyTable

--Create ChangeLogForMyTable table.
CREATE TABLE ChangeLogForMyTable
(
col1 int,
type varchar (10),
changedatetime datetime,
changeuser varchar(128)
)
GO

--Drop prior version of trgInsertToChangeLog trigger.
IF EXISTS (SELECT name FROM sysobjects
WHERE name = ’trgInsertToChangeLog’ AND type = ’TR’)
DROP TRIGGER trgInsertToChangeLog
GO

--Create trigger to monitor inserts.
CREATE TRIGGER trgInsertToChangeLog
ON MyTable
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
FOR INSERT
AS
DECLARE @col1value int

SET @col1value = (SELECT col1 FROM inserted)
INSERT INTO ChangeLogForMyTable VALUES(@col1value, ’INSERT’,
CURRENT_TIMESTAMP, SYSTEM_USER)
GO

--Drop prior version of trgDeleteToChangeLog trigger.
IF EXISTS (SELECT name FROM sysobjects
WHERE name = ’trgDeleteToChangeLog’ AND type = ’TR’)
DROP TRIGGER trgDeleteToChangeLog
GO

--Create trigger to monitor deletes.
CREATE TRIGGER trgDeleteToChangeLog
ON MyTable
FOR DELETE
AS
DECLARE @col1value int
SET @col1value = (SELECT col1 FROM deleted)
INSERT INTO ChangeLogForMyTable VALUES(@col1value, ’DELETE’,
CURRENT_TIMESTAMP, SYSTEM_USER)
GO

--Drop prior version of trgUpdateToChangeLog trigger.
IF EXISTS (SELECT name FROM sysobjects
WHERE name = ’trgUpdateToChangeLog’ AND type = ’TR’)
DROP TRIGGER trgUpdateToChangeLog
GO

CREATE TRIGGER trgUpdateToChangeLog
ON MyTable

FOR UPDATE
AS
DECLARE @col1value int
SET @col1value = (SELECT col1 FROM deleted)
INSERT INTO ChangeLogForMyTable VALUES(@col1value, ’UPDATE’,
CURRENT_TIMESTAMP, SYSTEM_USER)
SET @col1value = (SELECT col1 FROM inserted)
INSERT INTO ChangeLogForMyTable VALUES(@col1value, ’UPDATE’,
CURRENT_TIMESTAMP, SYSTEM_USER)
GO

The follow ing script should be run im m ediat ely after you creat e t he t r iggers wit h
the preceding scr ipt . I t also benefits from a fresh copy of t he MyTable t able, such
as the one generat ed by t he udfHigherThanMax script in t he “Creat ing a Scalar
UDF Wit hout Param et ers” sect ion. Th e script m akes a ser ies of changes to the
MyTable table. Aft er each change, it uses SELECT st at em ents t o ret urn t he
MyTable table and t he ChangeLogForMy Table table. The first change is t o add a
new row wit h t he value 25 for col1. Next it updat es t he value 25 to 26. Finally it
delet es the row in t he My Table table w it h a col1 value of 26.
--Demo_trgInsertUpdateDeleteToChangeLog
--Insert a new row into MyTable and display
--MyTable and ChangeLogForMyTable tables
INSERT INTO MyTable (col1)
VALUES (25)

SELECT *
FROM MyTable
SELECT *
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
FROM ChangeLogForMyTable

GO

--Update inserted row value and display
--MyTable and ChangeLogForMyTable tables.
UPDATE MyTable
SET col1 = 26
WHERE col1 = 25

SELECT *
FROM MyTable
SELECT *
FROM ChangeLogForMyTable
GO

--Delete updated row and display
--MyTable and ChangeLogForMyTable tables.
DELETE
FROM MyTable
WHERE col1 = 26

SELECT *
FROM MyTable
SELECT *
FROM ChangeLogForMyTable
GO

Exam ining the Result s pane contents will allow you t o follow t he changes t o t he
MyTable table as well as t he ChangeLogForMyTable table. The first display of the
ChangeLogForMyTable table sh ows a table with j ust one row and a col1 value of
25. I n t he next display of t he table, y ou can see t hree r ows. This is because an

updat e adds t w o rows t o t he table. I n its final appearance in t he results pane, the
ChangeLogForMyTable table contains four rows.
Enforcing a Business Rule on a Table
One of t he classic uses for triggers is t he enforcem ent of business rules. Aft er all,
the t rigger always fires befor e a change event. The T- SQL in t he tr igger can
assess t he change to m ake sure it conform s t o business rules before com m it t ing
the change t o a table. I f a change value doesn’t sat isfy a business rule, t he
trigger can t ake an appropriat e rem edy, such as rej ect ing t he change or rev ising
the change and inform ing t he user of any r em edial act ion.
The next sam ple enforces a sim ple business rule. The rule is t hat users can insert
only even num bers int o col1 of t he My Table t able. Your norm al business rules can
be subst antially m or e sophist icat ed t han t his sam ple, but t he triggers t o enforce
those rules can st ill use t he sam e logic. First you t est the change value t o m ake
sure it adheres to the rule. Second, if t he change value doesn’t confor m to the
business rule, your tr igger can perform an appropriat e rem edial act ion for t he
invalid change value. Third, if t he change value sat isfies t he business rule, you
insert it int o the table.
N ot e
Before running the sam ple script in t his sect ion, m ake sure
you drop all other tr iggers for the MyTable t able that can
conflict wit h t he sam ple below. The sam ple script on t he
book’s com panion CD rem oves all prior t riggers cr eated for
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
the MyTable table in t his chapter. For brevit y, t he list ing here
doesn’t show the code for dropping all t hese triggers.
The sam ple uses an I NSTEAD OF tr igger. Because t his t ype of tr igger fir es before
the change event, t here is no need t o roll back a t ransact ion for an invalid act ion.
The sam ple uses the m odulo operat or ( % ) to check whet her a num ber divides
evenly by 2. A rem ainder of 1 indicates an odd num ber. This outcom e calls for a
rem edial act ion. The act ion in t his inst ance is t o add 1 t o the input value from the

insert ed t able, const ruct a m essage indicating t he alt ernat iv e act ion t ak en, and
finally insert the new even num ber int o t he table. A rem ainder of 0 indicat es an
even num ber. Because ev en num bers sat isfy the business rule, t he t rigger can
j ust insert t he value from the insert ed table int o col1 of t he MyTable table.
Aft er t he creat ion of t he tr igger, t he script includes data m anipulat ion and SELECT
st at em ents t o t est the t rigger’s logic. You can run t he sam ple script and see the
trigger aut om at ically add 1 when the script at t em pts to input an odd num ber (25)
int o col1 in t he MyTable t able. On t he ot her hand, t he trigger m erely accept s t he
insert of an even num ber ( 24) into col1 in the MyTable table.
--trgInsteadOfInsert
--Drop prior version of trgInsteadOfInsert trigger.
IF EXISTS (SELECT name FROM sysobjects
WHERE name = ’trgInsteadOfInsert’ AND type = ’TR’)
DROP TRIGGER trgInsteadOfInsert
GO

--Create an INSTEAD OF trigger.
CREATE TRIGGER trgInsteadOfInsert
ON MyTable
INSTEAD OF INSERT
AS
DECLARE @col1value int
DECLARE @newcol1value int
DECLARE @strMsg varchar(400)

SET @col1value = (SELECT col1 FROM inserted)

--If inserted value is odd, make it even
--before inserting it.
IF @col1value%2 = 1

BEGIN
SET @newcol1value = @col1value + 1
SET @strMsg = ’The value you want to insert is: ’
+ CAST(@col1value AS varchar(3))
+ ’, but it violates a business rule.’ + CHAR(10) +
’ Therefore, I insert ’
+ CAST(@newcol1value AS varchar(3)) + ’.’
RAISERROR (@strMsg,16,1)
INSERT INTO MyTable (col1) VALUES(@newcol1value)
END
ELSE
INSERT INTO MyTable (col1) VALUES(@col1value)
GO

--Try to insert an odd value into col1 in MyTable.
INSERT INTO MyTable (col1) VALUES(25)

--Display the col1 values in MyTable.
SELECT *
FROM MyTable

--Delete the next even value after the odd value.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
DELETE
FROM MyTable
WHERE col1 = 26

--Display the col1 values in MyTable.
SELECT *
FROM MyTable


--Insert an even value into col1 in MyTable.
INSERT INTO MyTable (col1) VALUES(24)

--Display the col1 values in MyTable.
SELECT *
FROM MyTable

--Delete the new even col1 value in MyTable.
DELETE
FROM MyTable
WHERE col1 = 24

--Display the col1 values in MyTable.
SELECT *
FROM MyTable

Enforcing a Business Rule on a View
Two of the advantages of views are that they perm it you to insulat e your
dat abase schem a from t he user int erface for an application and t hat you can
select ively expose subset s from a table wit hout exposing all the dat a in a base
table. These feat ures perm it you to secure t he base table or tables for a view
from all or m ost users while you grant these sam e users access t o a subset of t he
dat a from the base table or tables through a view. Unfortunat ely, AFTER t riggers
never applied t o views, so previously you couldn’t enforce business rules wit h
triggers for views. SQL Server 2000 intr oduced I NSTEAD OF t riggers, w hich apply
to views. Therefor e, you can gain the benefit s of ex posing dat a t hr ough view s and
st ill be able t o enforce business rules via tr iggers.
The sam ple in t his sect ion dem onst rat es the syntax for applying a business rule
for insert s int o a view . The v iew is vewMy Table. This view ret urns all t he rows for

the colum n in t he MyTable table. The business rule is that t he insert ed col1 v alue
can be only 1 great er t han t he current m axim um in col1 of t he MyTable table.
N ot e
As wit h the sam ple script from t he preceding sect ion, you
should rem ove all t r iggers t hat can conflict wit h t he new
trigger. The version of the following sam ple on t he book ’s
com panion CD rem oves all prior triggers creat ed for t he
MyTable table in this chapter. For brevit y, the list ing here
doesn’t show the code for dropping all t hese triggers.
The script below st arts wit h t he cr eat ion of the vew MyTable v iew. Then the scr ipt
m oves on t o cr eat e a fresh v ersion of trgI nst eadOfI nsert For vewMyTable. No
special act ion is necessary for creat ing a trigger for a view. I n t he ON clause for
the CREATE TRI GGER st at em ent , j ust nam e t he view— vew MyTable, in t his case.
The trigger’s logic uses t he udfOneHigherThanMax UDF creat ed earlier in t his
chapter . You should run the code t o creat e t his UDF if it isn’t available. The logic
for enforcing t he business rule is t he sam e as for the previous t rigger, alt hough
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
the act ual business r ule is different. An I F…ELSE st at em ent t est s for t he validit y
of t he new value r elat iv e to t he business rule. I f the new value fails the test , the
trigger perform s a rem edial act ion. This act ion print s a m essage let t ing the user
know t he new value is invalid. Because the t rigger is an I NSTEAD OF tr igger,
there is no need t o roll back t he insert . I f t he new value is valid, t he t rigger
inserts the new value into vewMyTable.
Aft er t he script creat es the t rigger, t he script goes on to test t he tr igger by trying
to insert two new values. The first value violat es t he business rule, and t he
trigger rej ect s it . The second value sat isfies t he business rule, and t he t rigger
inserts the new value into col1 of t he MyTable t able. The final dat a m anipulat ion
st at em ent in t he scr ipt rem oves t he value new ly insert ed into t he vew MyTable
view t o rest ore the base table to it s init ial st at e.
--trgInsteadOfInsertForvewMyTable

--Drop prior version of vewMyTable view.
IF EXISTS(SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_NAME = ’vewMyTable’)
DROP VIEW vewMyTable
GO

--Create vewMyTable view.
CREATE VIEW vewMyTable
AS
SELECT *
FROM MyTable
GO

--Drop prior version of trgInsteadOfInsertForvewMyTable trigger.
IF EXISTS (SELECT name FROM sysobjects
WHERE name = ’trgInsteadOfInsertForvewMyTable’ AND type = ’TR
’)
DROP TRIGGER trgInsteadOfInsertForvewMyTable
GO

--Create an INSTEAD OF trigger for a view.
CREATE TRIGGER trgInsteadOfInsertForvewMyTable
ON vewMyTable
INSTEAD OF INSERT
AS
DECLARE @col1value int
SET @col1value = (SELECT col1 FROM inserted)
IF @col1value > dbo.udfOneHigherThanMax()
RAISERROR(‘Value too high.’,17,1)

ELSE
INSERT INTO vewMyTable (col1) VALUES(@col1value)
GO

--Attempting to insert a value of 100 fails
--through vewMyTable.
INSERT INTO vewMyTable (col1) VALUES(100)

SELECT * FROM vewMyTable
GO

--Attempting to insert a value one higher
--than the maximum value succeeds.
INSERT INTO vewMyTable (col1) VALUES(dbo.udfOneHigherThanMax())

SELECT * FROM vewMyTable
GO
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

--Remove inserted value.
DELETE
FROM vewMyTable
WHERE col1 = dbo.udfOneHigherThanMax()-1
GO


Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Cha pt er 6 . SQL Se rve r 2 0 0 0 XM L
Functiona lit y
When Microsoft SQL Server 2000 was launched, Microsoft com m itt ed it self t o

providing t he best Ext ensible Mark up Language ( XML) funct ionalit y possible. XML
is im portant because it prom ises to revolut ionize the way dat abase and Web
developers im plem ent dat a access and dat a m anipulat ion capabilit ies in their
solut ions. Micr osoft said it would revise t he init ial release wit h t im ely updat es t hat
included new funct ionalit y reflect ing t he rapidly evolv ing XML st andards and
relat ed developm ent issues.
As this chapter was being pr epared, Microsoft delivered on it s com m it m ent wit h
the release of it s lat est updat e— t he Microsoft SQL Ser ver 2000 Web Services
Toolk it. The toolk it follow s t wo earlier releases: XML for SQL Server 2000 Web
Release 1 and XML for SQL Server 2000 Web Release 2.
The Web Serv ices Toolkit is based on SQLXML 3.0 and includes t he SQLXML 3.0
inst allat ion package. Microsoft says t hat t he feat ures int roduced in SQLXML 1.0
and SQLXML 2.0 are included in t he SQLXML 3.0 package. See Chapt er 12 for
coverage of t he com pat ibilit y of t he t oolkit w it h t he t wo prior Web r eleases. I n
addit ion, see Cha pt er 1 3 for com m entary and sam ples using t he Web Serv ices
Toolk it.
You w ill gain from t his chapter an ov erall under st anding of XML funct ionalit y in
SQL Server wit h an em phasis on access to t hat funct ionalit y via T- SQL, XML
schem as and t em plat es, and hypert ext t ranspor t prot ocol (HTTP) . Chapter 12 will
refocus on XML so that you can build on the underst anding present ed her e while
you learn how t o tap the XML capabilit ies in SQL Serv er wit h Visual Basic .NET
and relat ed t echnologies, such as ADO.NET. Wit h XML, developers can build
incr edibly pow erful solut ions for ret rieving and m aint aining dat a ov er Web
connect ions. As the word get s out about how easy it is to creat e t hese solutions,
you will becom e an evangelist for using XML wit h SQL Ser ver.
This ch apt er relies on t he Nort hwind sam ple dat abase. The chapter sam ples add a
couple of new v iews and user-defined funct ions to t he dat abase for use wit h XML
files. T- SQL script s for creat ing t hese obj ect s are included wit h the sam ple files
for t his chapt er. The m ain r esource for the chapt er is a collect ion of nearly 20
XML files along w it h an assort m ent of URLs. Som e of t he URLs dem onst rat e direct

access t o a SQL Server dat abase, while ot her URLs invok e an XML file and access
a SQL Server database indir ect ly t hrough t he XML file.


Overview of XM L Support
I n learning about XML funct ionalit y, it is im port ant to recall t hat Micr osoft
int r oduced XML processing power t o SQL Server 2000 in m ult iple waves. This
m eans that selected XML feat ures available from t he init ial version of SQL Ser ver
2000 have been obsolet ed, or at least deprecated, by subsequent ly intr oduced
XML t echniques. This is because Web Release 1 and Web Release 2— and now t he
Web Serv ices Toolkit — added new XML funct ionalit y not available in t he init ial
release.
The overv iew of XML capabilit ies in t his sect ion has t wo parts. First it briefly
sum m arizes im portant XML feat ures for t he init ial release of SQL Server 2000 and
each of t he first two Web releases. Second it provides helpful inform at ion for
inst alling t he Web releases. See Chapter 12 and Chapt er 1 3 for m ore
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
inform at ion about the lat est Web release, the Microsoft SQL Ser ver 2000 Web
Services Toolkit .
Su m m a r y of XM L Fe a t ur es by SQL Serve r Relea se
The init ial release of SQL Server 2000 offered XML funct ionalit y in four m ain
areas.
• The abilit y to access SQL Server via HTTP. This for m of access relies on
the cr eat ion of a Micr osoft I nternet I nform at ion Ser vices ( I I S) virt ual
direct ory for each dat abase for which you prov ide access via HTTP.
• Support for XDR (XML- Dat a Reduced) schem as. You can use these
schem as to creat e XML- based views of SQL Server row sources, and you
can use a subset of t he XML Pat h (XPat h) query language to query these
views. Th e full XPat h specificat ion is a World Wide Web Consortium (W3C)
st andard (as outlined at ht tp: / / ww w.w3.org/ TR/ xpat h).

• Ret rieving and wr it ing XML dat a. Wit h t he FOR XML clause for the T- SQL
SELECT st atem ent , SQL Ser ver provides a rout e for reading it s dat a
sources and ret urning resu lt set s in XML form at . OPENXML is a new
funct ion that can ret urn a rowset based on an XML docum ent . Because T-
SQL enables the use of t he OPENXML funct ion in a m anner sim ilar to t hat
of t he OPENROWSET function, you can use I NSERT st at em ent s to populat e
dat a sources based on XML docum ent cont ents.
• Enhancem ent s for XML to Micr osoft SQL Server 2000 OLE DB provider
(SQLOLEDB) . These XML im prov em ent s com e along wit h version 2.6 of
Micr osoft Dat a Access Com ponents. Using t he new capabilit ies perm it s you
to pass XML- form at t ed dat a to a Com m and object and ret urn XML-
for m at t ed data from a Com m and obj ect . I n eit her case, t he dat a passes as
a St ream obj ect .
Web Release 1 was last updat ed on February 15, 2001. This r elease adds select ed
new XML capabilit ies to t he XML feat ures intr oduced when SQL Serv er 2000
initially shipped in t he fourt h quart er of 2000. As you can see, Microsoft wast ed
no t im e enhancing t he init ial capabilit ies. Web Release 1 creat es two m aj or
im prov em ent s along w it h a collect ion of m inor ones.
• Updat egram s enable t ransact ion- based dat a m anipulat ion using XML.
Updat egram s offer an XML-based sy ntax for insert ing, updat ing, and
delet ing records in a SQL Server row source. You can specify transact ions
for sets of operat ions wit hin Updat egram s so t hat all the dat a m anipulat ion
task s wit hin a t ransact ion occur or none occur. By using Updat egram s
inst ead of t he OPENXML funct ion, developers can im prov e t he perform ance
of t heir inserts, updat es, and delet es while sim plifying the coding.
• XML Bulk Load t arget s m oving m assive am ounts of XML-based dat a int o
SQL Server. This feat ure addresses the needs of dat abase adm inist rat ors
and ot hers who r egularly use eit her t he BULK I NSERT st at em ent or t he
bcp utilit y. I n a non-t ransact ion-based m ode, y ou can insert XML-
for m at t ed data fast er t han w it h Updat egram s or t he OPENXML funct ion.

• Select ed ot her Web Release 1 enhancem ents. New syntax offers you the
abilit y to specify w it h a param et er t he ret urn of binar y data from a SQL
Server dat a source. Virt ual direct ory m anagem ent tools expand t o offer
m ore precise control over how users can access a dat abase v ia a virtual
direct ory. Synt ax enhancem ents im prov e your abilit y t o m ap XML schem as
to SQL Serv er dat a sour ces and generally m anage XML tem plat es.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Web Release 2 cont inued t he pat t ern of int er m ediate releases that enhance the
XML funct ionalit y of SQL Server 2000. The last updat e for Web Release 2 was
Oct ober 15, 2001, eight m ont hs aft er Web Release 1. I n I nt er net tim e, t his gap is
long enough for a m aj or upgrade— and Microsoft took advantage of t he interval t o
offer significant new funct ionalit y. Web Release 2 is especially appropriate for
those planning to develop solut ions wit h a .NET language, such as Visual Basic
.NET. I highlight four m aj or areas of XML funct ionalit y and operat ion associat ed
wit h Web Release 2 :
• Com pliance wit h t he W3C sch em a specificat ion k now n as XML Schem a
Definition ( XSD) . While this release doesn’t drop support for t he
proprietary XDR schem a specification, Microsoft adds new funct ionalit y
that is com pliant only w it h t he indust ry-st andard XSD. Adopt ing XSD
schem as in y our ow n work will ensu re t he int eroperabilit y of your
applications wit h t hose of others who subscribe to t he XSD specificat ion.
• Client- side form att ing perm it s t he XML form at t ing of SQL Server row set s
on t he I I S server rat her t han t he dat abase serv er. This offers pot ent ial
scalabilit y advantages because m ult iple virt ual dir ect ories from different
I I S servers can point to t he sam e dat abase on a dat abase server. I n
addit ion, client- side form at ting rem oves processing from a database
server t hat m ight have ot her processing requirem ent s besides t hose for
one or m or e I I S servers.
• Two new dat a access com ponents enhance XML processing capabilit ies.
First , t he SQLXMLOLEDB provider facilit at es m ult iple object ives, including

client- side form at t ing and ActiveX Dat a Object s ( ADO) access t o Web
Release 2 funct ionalit y. SQLXMLOLEDB isn ’t a dat a prov ider; you use it in
com binat ion wit h SQLOLEDB, t he SQL Server ADO dat a provider. Second,
SQLXML Managed Classes explicit ly expose t he Web Release 2 obj ect
m odel, SQLXML 2.0, t o t he .NET Fram ework. By using t hese m anaged
classes, Visual Basic .NET developers can apply DiffGram s as an
alt ernative to Updat egr am s for dat a m anipulat ion task s.
• Side- by-side inst allat ion allow s Web Release 2 t o run on t he sam e
m achine wit h Web Release 1. When using Web Release 2 in this fash ion,
developers need t o explicitly reference the version t hey need for t heir
applications. For ex am ple, client- side pr ocessing is exclusively available
from v irt ual direct ories com pliant w it h Web Release 2. Sim ilarly, t he XML
Bulk Loading capabilit y is dependent on Web release. Each Web release
has its own dist inct DLL for im plem enting the XML Bulk Loading feat ure.
You m ust regist er the one that your applicat ion r equires.
W eb Relea se I nst allat ion
Bot h Web Release 1 and Web Release 2 ar e fully supported r eleases for SQL
Server 2000. These r eleases sh ouldn’t be confused wit h service packs t hat fix
problem s. While a Web release can r em edy a problem , it s m ain goal is t o add
new funct ionalit y not present in an ear lier release. I n order t o inst all Web Release
1 or 2, your com puter m ust have inst alled SQL Ser ver 2000 RTM ( Version
8.00.194) .
You can obtain t he Web releases from htt p: / / w ww.m icr osoft .com / sql/ downloads/ .
Click t he link labeled XML For SQL Server Web Release 1 (WR1) for Web Release
1. Click t he link labeled XML For SQL Server Web Release 2 ( SQLXML 2.0) for
Web Release 2. You will t ypically be downloading t he releases t o a com put er
equipped w it h an I I S server. Therefore, you should t ake the norm al pr ecautions
to guard against acquiring a virus during your I nter net connect ion tim e.
Aft er you com plet e inst alling a Web release, your Program s m enu is updat ed wit h
an it em for the release. Web Release 1 adds a new m enu it em labeled Micr osoft

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
SQL Server XML Tools, which includes a single it em — XML For SQL
Docum entat ion. This it em opens t he Softw are Developm ent Kit (SDK) for the
package, w hich includes docum ent at ion on t he feat ures of t he release.
Web Release 2 adds SQLXML 2 .0 to t he Program s m enu. The SQLXML 2.0 m enu
cont ains t hr ee it em s: Configure I I S, SQL 2.0 Docum ent at ion, and SQLXML 2.0
Readm e. Configure I I S offers a new wizard for configuring a virt ual dir ect ory to
int eract wit h SQL Server (updat ed from the wizard in t he init ial release) . The
inst allat ion of Web Release 2 also offers a new SQLI SAPI filt er and SQLXML DLL
files for t he m iddle t ier t hat replace t he versions shipping wit h t he init ial release
of SQL Serv er 2000. Creat ing a virt ual direct or y w it h the Configure I I S m enu it em
perm it s your applications t o t ak e advant age of t he new feat ures enabled by these
com ponents. You can also use t he new wizard t o upgrade virt ual dir ect ories t o
take advant age of feat ures introduced wit h Web Release 2. I nst alling t he files for
Web Release 2 doesn ’t cause t he rem oval or ov erwr it ing of t he files for Web
Release 1. I t is t his feat ur e t hat perm it s you to t ap t he feat ures of eit her release
side by side on t he sam e com put er.


XM L Form at s an d Schem a s
XML is a rich and deep t ech nology t hat prom ises t o adv ance com put ing in t he
first decade of t he tw enty- first cent ury as m uch as or m ore than Visual Basic did
in t he last decade of t he t went iet h century. This sect ion delivers an int roduct ion
to XML- form at ted dat a t hat part icularly target s current and pot ent ial applications
of XML wit h SQL Server. Su bsequent sect ions will highlight how to use XML wit h
SQL Server 2000; t his sect ion focuses on t hree XML t opics that will equip you t o
underst and t he m at erial in those lat er sect ions. First I st art by descr ibing the
overall sy nt ax for XML docum ent s. Second I present the basics of XML schem as
as a device for validat ing XML docum ents. Third I review XML annot at ed schem as
as a m eans of creat ing a view for a SQL Ser ver dat a source.

XM L Docum ent s
XML is especially well suit ed for represent ing st r uct ured docum ent s, such as
inv oices and row sources in a dat abase. There is an im m ense body of literat ure
about XML. Aside from t his sect ion, one place t o st art fam iliarizing yourself w it h
XML conventions for represent ing dat a is the World Wide Web Consortium (W3C)
sit e at ht t p: / / w ww.w3c.org/ XML. This sit e cont ains link s to m any valuable XML
resources, such as the W3C Recom m endat ion for XML 1.0. I n addit ion, there are
m any XML- based t ech nologies, such as XML Schem a, XPat h, XSL, and XSLT.
Links at t he W3C m ain Web sit e can serve as a st arting point for learning about
these r elated t echnologies.
A t ypical XML docum ent can represent dat a wit h a collect ion of t ags and a
st art ing declarat ion. These t ags ar e sim ilar in som e ways to HTML t ags, but they
differ in im port ant ways. XML t ags denot e dat a elem ents inst ead of how to form at
dat a. HTML assigns a pr ecise m eaning to t ags. For exam ple, t he < p> tag m eans
st art a new paragraph. XML, on t he ot her hand, doesn’t assign a predet erm ined
m eaning t o a t ag. I ndeed, the sam e tag can hav e a differ ent m eaning in different
XML docum ents, and it is even possible for one t ag t o have different m eanings in
the sam e XML docum ent. By using nam espaces, developers can resolve pot ential
conflict s when t he sam e tag has t wo or m ore different m eanings in t he sam e
docum ent .
XML lit erat ure typically refers t o t he t ags in a docum ent as elem ents. An elem ent
can contain other elem ent s, a dat a value, or bot h ot her elem ents and a dat a
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
value. Elem ents can have parent , child, and sibling relat ionships wit h one
anot her. When an elem ent contains anot her one, the container elem ent is the
parent elem ent and the cont ained elem ent is t he child elem ent. For exam ple,
< ShipperI D> , < Com panyNam e> , and < Phone> tags can be child t ags of a par ent
tag < Shippers> in an XML docum ent w it h dat a for t he Shippers t able. The tags
betw een a part icular inst ance of < Shippers> and < / Shippers> can denot e a row
in t he Shippers t able. XML docum ents t hat cont ain m ultiple occurrences of at

least one t ag, such as < Sh ippers> , m ust have one t ag set t hat cont ains all ot her
tags, such as < root > and < / root > . This out erm ost t ag set can occur just once
wit hin an XML docum ent .
An XML tag ( or elem ent ) can have one or m ore att ribut es. The use of at t ributes is
opt ional. At t ributes appear wit hin t he t ag for an elem ent , such as < Sh ippers> .
You designat e att ribut es wit h nam e- value pairs. The nam e denot es t he at t ribute’s
nam e, and t he value depict s it s dat a value. Dat a values can appear in eit her
single or double quot at ion m arks following an equal sign behind t he at t ribut e
nam e. You can represent the dat a for a table wit h elem ent values, at t ribut e
values, or bot h.
The follow ing docum ent depict s t he Shippers t able dat a from the Northwind
dat abase represent ed w it h elem ents and no att r ibut es. Not ice t hat the first set of
angle bracket s ( < > ) declares the docum ent as an XML docum ent in ver sion 1
for m at . The ut f- 8 designat ion for encoding denot es a convention for convert ing
charact ers t o bit sequences inside a com put er. Because t he < Shippers> tag is
repeat ed three t im es in the docu m ent , a par ent tag set that appears j ust once is
necessary; t he < root > and < / root > tags m eet this requirem ent . Th e nam e root
has no special m eaning; any ot her legit im ate nam e for a tag, such as
ShippersRoot , can replace r oot. The < Shippers> tag is the par ent of t he
< ShipperI D> , < Com panyNam e> , and < Phone> tags. These latt er t hree t ags are
siblings of one anot her.
<?xml version="1.0” encoding="utf-8”?>
<!--Available in Chapter 06 code samples as shippers_elements.xml-->
<root>
<Shippers>
<ShipperID>1</ShipperID>
<CompanyName>Speedy Express</CompanyName>
<Phone>(503) 555-9831</Phone>
</Shippers>
<Shippers>

<ShipperID>2</ShipperID>
<CompanyName>United Package</CompanyName>
<Phone>(503) 555-3199</Phone>
</Shippers>
<Shippers>
<ShipperID>3</ShipperID>
<CompanyName>Federal Shipping</CompanyName>
<Phone>(503) 555-9931</Phone>
</Shippers>
</root>

The next XML docum ent shows t he sam e dat a from the Shippers t able as the
preceding one. I n t his inst ance, t he docum ent’s form att ing represent s dat a values
wit h att r ibutes inst ead of elem ent s or tags. The declar at ion for t his XML
docum ent inst ance is t he sam e as in t he pr eceding sam ple. At t ribut es appear in a
paired arr angem ent — fir st the at t ribut e nam e follow ed by an equal sign, and
second t he at t ribut e value in double quot at ion m arks. The colum n values for each
row in the Shippers t able appear wit hin a separat e < Shippers> t ag in the
docum ent . The trailing / charact er wit hin each < Shippers> tag is an alt ernat ive to
designat ing < / Sh ippers> to close t he < Shippers> tag.
<?xml version="1.0” encoding="utf-8” ?>
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
<!--shippers_attributes.xml-->
<root>
<Shippers ShipperID="1” CompanyName="Speedy Express"
Phone="(503) 555-9831” />
<Shippers ShipperID="2” CompanyName="United Package"
Phone="(503) 555-3199” />
<Shippers ShipperID="3” CompanyName="Federal Shipping"
Phone="(503) 555-9931” />

</root>

Figure 6-1 sh ows t he Shippers t able in t he XML form at for each of t he preceding
XML docum ent files. The figure reveals how t he XML appears wit hin a browser.
Not ice t hat you can read t he dat a! Many ot her dat a form at s don’t appear so
readable in a brow ser. XML’s charact er -based form at for representing dat a is one
of t he advantages of XML over ot her form at s for represent ing dat a. I n t he
browser view of sh ippers_elem ents.xm l, you can collapse t he dat a for any
indiv idual row in t he Shippers table by click ing t he m inus sign ( - ) next t o the
opening < Sh ippers> tag for a row. You can collapse the dat a for all t hree rows by
clicking the m inus sign next t o t he opening < root > t ag for eit her docu m ent .
Figur e 6 - 1 . A pair of scr ee n sh ots illust rat ing tha t users can read ily
ex am ine th e cont en t s of an X M L docum en t in a brow se r.

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
XM L Schem a s
An XML schem a prov ides a fram ework for describing the st ruct ure and v alidat ing
the cont ents of an XML docum ent . Wit h an XML schem a, you can know what
values ar e legit im at e for any tag or at t ribut e inst ance. You can also use schem as
to place const raint s on t he range of acceptable values for a dat a elem ent. By
specify ing cardinality for elem ent s wit h t he m inOccurs and m axOccurs elem ent
att ribut es, you can specify how m any elem ent inst ances ar e legit im at e in an XML
docum ent . You can additionally designat e whet her an elem ent has any at t ribut es,
and t he relationships am ong elem ents.
The W3C approv ed on May 2, 2001, a recom m endat ion
(htt p: / / www.w3.org/ 2001/ XMLSchem a) that serves as t he indust ry st andard for
expressing XML schem as. Developers refer to t he W3C schem a st andard as an
XSD schem a. St art ing w it h Web Release 2, SQL Ser ver adopted t his st andard.
Before Web Release 2, SQL Server worked wit h XDR schem as— a precursor of the
XSD schem a. This chapt er uses exclusively XSD schem as.

The follow ing script represent s t he shell for a schem a. Not ice t hat an XSD schem a
is an XML docu m ent because it st art s w it h an XML declarat ion. Th is m eans t hat
you can describe an XSD schem a wit h t he sam e syntax t hat y ou use for any XML
docum ent . I n addit ion, not ice t he reference t o t he nam espace at
ht t p: / / www.w3.org/ XMLSchem a. This nam espace defines a set of t ags and
att ribut es for defining schem as as XML docu m ent s. The xsd designat ion for the
nam espace is arbit rar y. ( For exam ple, you can use xs inst ead.) An XSD schem a
can have m ore than one nam espace reference. Each nam espace can reference a
different set of tags and at t ribut es. By using a dist inct nam espace designat or for
each nam espace, y ou can resolv e conflict s for ident ically nam ed tags and
att ribut es bet ween t wo different nam espaces. The shell refers t o t he tags and
att ribut es wit h t he xsd nam espace designat ion. The sch em a t ag or elem ent ,
which m arks t he beginning and end of a schem a, is from t he nam espace
designat ed by xsd.
<?xml version="1.0” encoding="UTF-8”?>
<xsd:schema xmlns:xsd="
...
</xsd:schema>

A basic underst anding of several form at t ing conventions can help you get st arted
writ ing your own schem a ( or at least equip you to read t hose w rit t en by ot hers) .
Elem ent declarat ions can be for a sim ple or a com plex t ype. A com plex ty pe
elem ent has at least one child elem ent or one att ribut e. You can explicitly define
a child elem ent wit hin a parent elem ent or refer to a child elem ent defined
elsewhere within a schem a. A sim ple type elem ent has neit her a child elem ent
nor an at t ribut e. I n addition, t he declarat ion for a sim ple t ype elem ent classifies
the dat a type for t he elem ent according t o one of t he built - in XSD dat a t ypes. The
XSD dat a types generally cor respond t o SQL Server dat a types. See the “Dat a
Type Coercions and t he sql: dat at ype Annot at ion” topic in t he online
docum ent at ion for Web Release 2 for a det ailed discussion of the sim ilar it ies and

differences bet w een SQL Server and XSD dat a types. I n addit ion t o elem ents, a
schem a can also specify at t ributes. According t o the W3C convent ion, t he
att ribut es for a com plex t ype elem ent are designat ed follow ing t he specifications
for or refer ences t o any child elem ent s.
The follow ing XML docum ent is t he XSD schem a for t he shippers_ elem ents.xm l
docum ent file present ed in the preceding sect ion. Follow ing t he schem a t ag wit h
the nam espace declarat ion, the sch em a declares a com plex elem ent type for t he
root t ag. The root elem ent is com plex because it has child elem ents, nam ely, one
or m ore Shippers elem ent s. The exact upper lim it for t he num ber of Sh ippers
elem ents wit hin t he root elem ent is unbounded. (See the assignm ent for
m axOccurs.) The m inOccurs at t ribute for t he choice specificat ion doesn’t appear
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
in t he sch em a, but its default value is 1. Therefor e, t o allow an XML docum ent
wit h no Shippers elem ent s, designat e the value 0 for m inOccurs. Not ice t hat the
Shippers elem ent doesn’t appear nest ed within the root elem ent declar ation.
I nst ead, the root elem ent declarat ion uses the ref at t ribut e t o refer t o t he
Shippers elem ent.
The Shippers elem ent declarat ion follows t he r oot elem ent declarat ion. The
Shippers elem ent has t hree child elem ents— ShipperI D, Com pany Nam e, and
Phone. I n t he following schem a, the declarat ions for t he child elem ents appear
nest ed w it hin t he Shippers elem ent . Each child elem ent has a dat a type derived
from an XSD built -in dat a type, such as the int eger or st ring dat a type. The
rest rict ion elem ent in t he child declarat ions denot es the dat a t ype for t he child
elem ents from t he built - in dat a t ype. I n t he case of t he ShipperI D elem ent , t he
declarat ion lim it s t he elem ent’s values t o integers. I n t he case of the
Com panyNam e and Phone elem ents, the declarat ions lim it t he elem ent values t o
st rings. I n addit ion, t he m axim um lengt h is 40 and 24 for t he Com panyNam e and
Phone elem ents, r espect ively. By assigning m inOccurs t o 0, the sch em a perm it s
the Phone elem ent to be opt ional for each Shippers elem ent . The ShipperI D and
Com panyNam e elem ent s are required child elem ent s for each Shippers elem ent .

<?xml version="1.0” encoding="UTF-8”?>
<!--shippers_elements.xsd-->
<xsd:schema xmlns:xsd="
<xsd:element name="root">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element ref="Shippers"/>
</xsd:choice>
</xsd:complexType>
</xsd:element>
<xsd:element name="Shippers">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="ShipperID">
<xsd:simpleType>
<xsd:restriction base="xsd:integer"/>
</xsd:simpleType>
</xsd:element>
<xsd:element name="CompanyName">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="40"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="Phone” minOccurs="0">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="24"/>
</xsd:restriction>

</xsd:simpleType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>

The schem a for t he shippers_at t ribut es.xm l docum ent file appears next . The
Shippers elem ent in this schem a has no child elem ent s because of t he layout of
the shippers_at t ribut es. xm l docum ent . Nev ert heless, t he Shippers elem ent st ill
requires a com plex t ype elem ent declaration because t he Shippers elem ent has
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
three at tributes. Not ice that y ou can use t he sam e sim pleType elem ent s for
declaring at t ribut es t hat you use for declaring elem ent s in an XML docu m ent. I n
spit e of using t he sam e sim pleType elem ents as t he preceding schem a, t his
schem a differs from the preceding one by declaring ShipperI D, Com panyNam e,
and Phone as at t ribut es inst ead of elem ents.
<?xml version="1.0” encoding="UTF-8”?>
<!--shippers_attributes.xsd-->
<xsd:schema xmlns:xsd="
<xsd:element name="root">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element ref="Shippers"/>
</xsd:choice>
</xsd:complexType>
</xsd:element>
<xsd:element name="Shippers">
<xsd:complexType>
<xsd:attribute name="ShipperID">

<xsd:simpleType>
<xsd:restriction base="xsd:integer"/>
</xsd:simpleType>
</xsd:attribute>
<xsd:attribute name="CompanyName">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="40"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
<xsd:attribute name="Phone” type="string">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="24"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
</xsd:complexType>
</xsd:element>
</xsd:schema>

Annot at ed Schem a s
Up unt il t his point , I used schem as to specify the cont ent s of XML docum ent s.
However, m ost of you reading t his book probably care m ore about the dat a in
your SQL Server dat abase t han in an XML docu m ent. XML docum ents are a
convenient way of sh ow ing and sharing dat a over the Web. I nst ead of schem as
m erely defining XML docum ents, you would probably prefer t hat XML docum ents
point t o SQL Ser ver dat abases and expose dat abase cont ents. This role allow s
schem as to provide Web-based v iews for SQL Server dat abase content s.

Annot at ed schem as when used wit h a virt ual directory on an I I S server allow you
to der iv e a view of t he dat a in a SQL Server dat abase. An annotat ed schem a
cont ains special elem ent s and at t ribut es t hat specify how t o link it t o a SQL
Server dat abase. The XML docum ent that exposes the view can appear in a Web
browser. The cont ents of the XML docum ent will confor m to t he schem a design
and any param et ers passed direct ly from the browser ( or an int erm ediat e XML
docum ent ). A browser can bot h init iat e t he request for t he XML view and display
the view as an XML docum ent . I n addit ion, a br owser can launch t he process by
point ing t o an XML docu m ent in a v irtual direct ory on an I I S server t hat invok es a
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
schem a linking to a row source. SQL Server has a special tool for creat ing v irt ual
direct ories on I I S server s that point t o specific SQL Server dat abases. These
virtual dir ect ories perm it annot at ed schem as t o connect to a SQL Ser ver dat abase
and der ive a row set .
N ot e
One of the innovat ions of Web Release 2 is t hat t he
form at t ing of t he ret urned rowset can t ake place on t he I I S
server inst ead of SQL Server. By transferring t he form at t ing
of the returned rowset from t he dat abase server t o the I I S
server , Microsoft can event ually provide views based on
annotated schem as for ot her than SQL Server databases.
This sect ion introduces the basics of annot at ed schem a design and use. A lat er
sect ion, “Virtual Direct ory Managem ent,” drills down on virt ual direct or ies. An
annot ated schem a is an XML docum ent just like a norm al XSD schem a. However,
you norm ally writ e it wit hout the XML v ersion declarat ion. I n addit ion, you m ust
add a new nam espace reference (schem as- m icr osoft - com : m apping-schem a) to
the schem a sh ell t o accom m odat e sp ecial annot at ion elem ents and at t ributes.
This Microsoft m apping nam espace support s the special feat ures t hat perm it
annot at ion of XSD schem a so t hey link t o one or m ore row sources in a SQL
Server dat abase. The sql designat or for the nam espace is arbit rary ; you can use

any ot her legit im at e XML nam e.
<xsd:schema xmlns:xsd="
xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
...
</xsd:schema>

Two at t ribut es for linking a schem a t o a row source in a dat abase include the
relat ion att r ibut e and t he field at t ribut e. Precede t hese at t ribut e nam es and any
other that you use for annot at ing your schem a wit h t he designat or for the
Micr osoft m apping nam espace. The relat ion at t ribute creates a link bet ween a
com plex elem ent and a SQL Server row source. Using the r elat ion at t ribute let s
you cr eate an alias in y our annot at ed schem a for t he row source nam e in a SQL
Server dat abase. The schem a will att em pt t o m at ch the child elem ents and
att ribut es for the com plex elem ent t o the colum ns from the row source. I f t he
att ribut es and child elem ent s have nam es t hat m at ch colum n nam es in the r ow
source, you don’t need t o specify a field at t r ibut e for t he at t ribut e or elem ent. I f
the at t ribute or child elem ent nam e doesn’t m at ch t he nam e for a colum n in t he
row source, you can specify the field at t ribut e. Wit h t he field at t ribut e, you can
explicitly link an elem ent or att r ibute to a colum n in t he row source specified by a
relat ion att r ibut e.
N ot e
I f a com plex element nam e in a schem a m atches a row
source nam e in a dat abase, you don’t need to designat e t he
correspondence bet w een t he t wo with the relat ion at tribute.
The follow ing annot at ed schem a dem onst rat es t he use of t he relation and field
att ribut es. The schem a form at s an XML docum ent wit h a com plex elem ent t ype
nam ed xm lShippers t hat has t wo child elem ent s, xm lCom panyNam e and
xm lPhone, and an at t ribute, ShipperI D. Not ice t hat t he relat ion and field
att ribut es appear wit h a sql pr efix to specify t he nam espace for defining the
att ribut es. The sq l: r elat ion at t ribut e point s t he xm lShippers elem ent t o t he

Shippers row source. The sql: field at t ribut es for the xm lCom panyNam e and
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
xm lPhone elem ent s link these elem ents to t he Com panyNam e and Phone colum ns
in t he Shippers r ow source. Because the ShipperI D at t ribut e nam e m at ches a
colum n in t he Shippers row source, it doesn’t requir e a sql: field at t ribut e set t ing
t o link it to a colum n within t he row source.
<xsd:schema xmlns:xsd="
xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
<!--xmlShippersSchema.xml-->
<xsd:element name="xmlShippers” sql:relation="Shippers” >
<xsd:complexType>
<xsd:sequence>
<xsd:element name="xmlCompanyName”
sql:field="CompanyName”
type="xsd:string” />
<xsd:element name="xmlPhone”
sql:field="Phone”
type="xsd:string” />
</xsd:sequence>
<xsd:attribute name="ShipperID” type="xsd:integer” />
</xsd:complexType>
</xsd:element>
</xsd:schema>

Wit h t hr ee m or e st eps, you can ret urn an XML docum ent based on t he Shippers
row source.
1. Save t he annot at ed schem a in a virt ual direct ory configured t o connect t o
the Nort hw ind dat abase. Because t he Nort hwind table cont ains a table
nam ed Shippers, this defines t he row source in t he annot at ed schem a.
2. Creat e a new XML docum ent , called a t em plat e, t hat invokes t he

annot ated schem a. By invoking the query with XPat h sy ntax, t he tem plat e
file can cause t he annot at ed schem a t o ret urn a view of the Shippers t able
as an XML docum ent.
3. Nav igat e t o t he tem plat e from a browser t o ret urn t he view specified by
the t em plat e to t he browser’s docum ent window.
The follow ing XML docum ent illust rat es t he synt ax for referring to t he preceding
annot ated schem a in xm lSh ippersSch em a.xm l. The specificat ion r equires t he
schem a t o reside in a special t em plat e folder wit hin t he virt ual direct ory, but you
can explicit ly designat e anot her source for the annot at ed schem a file. The act ual
query sy ntax sim ply references t he elem ent wit h t he sql: r elat ion at t ribut e set t ing,
nam ely xm lSh ippers. This form of an XPat h query request s the ret urn of all the
rows fr om the Shippers table. The XPat h query is equivalent to SELECT * FROM
Shippers in T- SQL.
<ROOT xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<!--xmlShippersSchemaT.xml-->
<sql:xpath-query mapping-schema="xmlShippersSchema.xml">
/xmlShippers
</sql:xpath-query>
</ROOT>

The top screen shot in Fig ur e 6-2 shows t he Shippers table in XML form at based
on t he annot at ed schem a in xm lSh ippersSchem a.xm l and the t em plat e file
(xm lShippersSch em aT.xm l) t hat queries t he schem a. The browser’s Address box
shows t he pat h t o t he t em plat e file t hat cont ains the XPat h query. The t em plat e
resides on an I I S server nam ed ccs1. The tem plat e is in t he t em plat e folder of t he
MyNw ind v irt ual direct ory. The use of t he nam e tem plat e for t he tem plate folder
is arbit rary . Any ot her nam e w ill serve equally well. The XML docum ent in t he
browser w indow follows the form at of the annot ated schem a. Not ice that
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

×