0% found this document useful (0 votes)
91 views22 pages

SQL 2005 XML

sql 2005 XML

Uploaded by

andera4u
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views22 pages

SQL 2005 XML

sql 2005 XML

Uploaded by

andera4u
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 22

2007 Microsoft Corporation. All rights reserved.

Microsoft SQL 2000 Technical Articles

SQLXML Managed Classes


Scott Swigart 3 Leaf Sol tions March 2002 Applies to! Microsoft" SQL Server# 2000 Microsoft $is al St dio" .%&T Summary: 'ow to se SQL(ML Managed Classes for .%&T code to retrieve (ML fro) a Microsoft SQL Server data*ase or to generate (ML on the client side+ sing ad hoc , eries+ stored proced res+ annotated sche)as with (-ath+ or (ML te)plates. ./0 printed pages1 Contents 2ntrod ction SQL(ML Managed Classes 3*4ect Model 5sing SQL(ML Managed Classes Concl sion A*o t the A thor

Introduction
Co)panies have fo nd SQL(ML to *e a sef l technolog6 for a n )*er of scenarios. A co)pan6 )a6 receive (ML doc )ents in vario s for)ats and wish to store this data in a Microsoft" SQL Server# 2000 data*ase+ or a co)pan6 )a6 need to serve (ML doc )ents in vario s for)ats for trading partners. 2n addition+ (ML doc )ents )a6 *e transfor)ed sing st6le sheets to target vario s *rowsers+ handheld -Cs+ or other devices. 7or these scenarios+ SQL(ML allows 6o to send (ML data to and retrieve it fro) SQL Server. This capa*ilit6 )eans that the developer is not re, ired to a thor and )aintain all the code needed to transfor) (ML into so)e other for)at for cons )ption *6 the data*ase. SQL(ML Managed Classes allow 6o to a thor .%&T code that ta8es advantage of the (ML feat res provided *6 SQL(ML 3.0. 9o can write )anaged Microsoft $is al C:# or $is al ;asic" .%&T code that tili<es 73= (ML+ (ML te)plates+ annotated sche)as+ and >iff?ra)s. This white paper will e@plain the )echanics of sing SQL(ML Managed Classes for a variet6 of scenarios. This paper is *ased on SQL(ML 3. 9o can download the latest release of SQL(ML A http!BB)sdn.)icrosoft.co)Bs,l@)lB C .

SQLXML Managed Classes Object Model


Three pri)ar6 classes are sed to access the (ML f nctionalit6 of SQL Server. These are!

SqlXmlCommand. 5sed to send a TransactDSQL state)ent to the data*ase+ e@ec te a stored proced re+ or , er6 the data*ase sing other technologies .s ch as annotated

sche)as and (ML te)plates1 and get the res lts *ac8 as (ML. This o*4ect s pports a wide range of options+ which are disc ssed in detail later in this doc )ent.

SqlXmlParameter. 5sed to specif6 the val e for a para)eter in the co))and. This can *e a para)eter to an ad hoc , er6+ stored proced re+ (-ath , er6+ or (ML te)plate. SqlXmlAdapter. 5sed to pop late a data*ase with an (ML >iff?ra). ataSet o*4ect with an (ML res lt set+ or pdate the

!sing SQLXML Managed Classes


The SqlXmlCommand class is the pri)ar6 class sed when retrieving data fro) SQL Server in (ML for)at. This class allows 6o to send , eries to the data*ase and retrieve the res lts as a strea) or Xml"eader o*4ect+ or to send the o tp t directl6 into another strea). The , er6 can *e para)eteri<ed+ and with the help of the SqlXmlParameter class+ 6o can specif6 the val es for these para)eters. 9o can e@ec te , eries sing ad hoc TransactDSQL state)ents+ stored proced res+ annotated sche)as and (-ath+ and te)plates. 9o can have the (ML ret rned directl6 fro) the data*ase+ or do the conversion to (ML on the client side *6 si)pl6 setting a propert6. 7inall6+ 6o can have the SqlXmlCommand o*4ect a to)aticall6 appl6 a st6le sheet to the (ML res lt set+ perfor)ing an6 re, ired transfor)ation.

SqlXmlCommand
This section descri*es how to se SqlXmlCommand to retrieve (ML data fro) SQL Server. Ehen a thoring )anaged code+ 6o often se classes fro) a variet6 of na)espaces. The code in this paper ass )es that 6o have incl ded the following F singF directives!

using System; using System.Data; using Microsoft.Data.SqlXml; using System.Xml; using System.Xml.Xsl; using System.Xml.XPath; using System.IO; using System.Security.Cryptography;
=egardless of the scenario for retrieving data+ one set p for SqlXmlCommand is niversal. SqlXmlCommand s pports a single constr ctor that ta8es an Active( >ata 3*4ects .A>31 connection string as an arg )ent+ as shown *elow!

static string Northwin ConnString ! "Pro#i er!S$%O%&D';Ser#er!(local); ata*ase!Northwin ;" + "Integrate Security!SSPI"; SqlXmlComman cm ! new SqlXmlComman (Northwin ConnString);

The code sa)ples in the re)ainder of this white paper ass )e that the NorthwindConnString varia*le has *een initiali<ed. Ehen an (ML res lt set is ret rned fro) SQL Server 2000+ it is t6picall6 an (ML frag)ent+ lac8ing a single root tag. Therefore+ it is i)portant to set the "oot#ag propert6 of SqlXmlCommand so that the res lting (ML is well for)ed+ as follows!

cm .,oot-ag!"pro ucts";
SqlXmlCommand$%&ecuteStream The first e@a)ple of retrieving (ML data ses the %&ecuteStream )ethod. This )ethod ret rns the (ML data fro) SQL Server as a si)ple .%&T strea) instance!

SqlXmlComman cm ! new SqlXmlComman (Northwin ConnString); cm .,oot-ag!"pro ucts"; cm .Comman -ype ! SqlXmlComman -ype.Sql; cmd.CommandText= "SELECT * FROM products FOR XML AUTO"; StreamReader sr = ne StreamReader!cmd.ExecuteStream!"";

3ne reason for ret rning the res lts as a strea) )ight *e to perfor) an operation on the doc )ent as a whole witho t regard for its contents. S ch an operation co ld incl de co)pressing or encr6pting the res lt set. 2n this case+ the (ML res lts are not treated as an act al (ML doc )ent+ * t rather as a strea) of *6tes. 9o can se the following code to >&S encr6pt the (ML data that was ret rned fro) the previo s e@a)ple!

'yte./ 0ey ! new 'yte./ 123 453 653 2223 73 8443 263 829:; 'yte./ i# ! new 'yte./ 1283 8753 2;<3 <63 2;<3 83 463 2;:; D&SCryptoSer#icePro#i er Crypto ! new D&SCryptoSer#icePro#i er(); =ileStream =Stream ! =ile.Open(>"c?@&ncrypte .*in"3 =ileMo e.Create3 =ileAccess.Brite); CryptoStream &ncStream ! new CryptoStream(=Stream3 Crypto.Create&ncryptor(0ey3 i#)3 CryptoStreamMo e.Brite); StreamBriter SB ! new StreamBriter(&ncStream); SB.Brite(sr.,ea -o&n ()); SB.Close();

SW.Write(sr.ReadToEnd()); reads the (ML inp t strea) and sends the data thro gh CryptoStream and FileStream to store the encr6pted (ML on dis8.
SqlXmlCommand$%&ecute#oStream =ather than ret rn the (ML data fro) SQL Server as a si)ple Stream o*4ect+ 6o )a6 wish to send the (ML res lt set directl6 to the destination witho t )odification. 2n this case+ 6o can se the %&ecute#oStream )ethod to send the res lting (ML directl6 to a 'ileStream o*4ect+ a (et)or*Stream o*4ect+ or+ in the case of AS-.%&T+ the "esponse o*4ect. The following code sends the (ML res lts directl6 to a 'ileStream o*4ect. The Process class is then sed to displa6 the res lts in 2nternet &@plorer .ass )ing that (ML files are associated with 2nternet &@plorer+ which is the defa lt config ration1.

SqlXmlComman cm ! new SqlXmlComman (Northwin ConnString); cm .,oot-ag!"pro ucts"; cm .Comman -ype ! SqlXmlComman -ype.Sql; cm .Comman -eCt! "S&%&C- D =,OM pro ucts =O, XM% AE-O"; F#$eStream % = ne F#$eStream!&"c'(products.xm$")F#$eMode.Create";

cmd.ExecuteToStream!%"; %.C$ose!"; S*stem.+#a,nost#cs.-rocess.Start!&"c'(products.xm$"";


This code retrieves all the rows and col )ns fro) the products ta*le and displa6s the res lts as follows!

FGCml #ersion!"2.5" enco ing!"utfH6" GI FOr ersI FOr er &mployeeID!"4" CustomerID!"JIN&-" Or erID!"25876"I FOr erDateI2;;KH59H57-55?55?55FLOr erDateI F,equire DateI2;;KH56H52-55?55?55FL,equire DateI FShippe DateI2;;KH59H2K-55?55?55FLShippe DateI FShipJiaI<FLShipJiaI F=reightI<8.<6FL=reightI FShipNameIJins et alcools Che#alierFLShipNameI FShipA ressI4; rue e lMapos;A**ayeFLShipA ressI

FShipCityI,eimsFLShipCityI FShipPostalCo eI42255FLShipPostalCo eI FShipCountryI=ranceFLShipCountryI

FLOr erI FOr er &mployeeID!"K" CustomerID!"-OMSP" Or erID!"2587;"I FOr erDateI2;;KH59H54-55?55?55FLOr erDateI F,equire DateI2;;KH56H2K-55?55?55FL,equire DateI FShippe DateI2;;KH59H25-55?55?55FLShippe DateI FShipJiaI2FLShipJiaI F=reightI22.K2FL=reightI FShipNameI-oms SpeNialitOtenFLShipNameI FShipA ressI%uisenstr. 76FLShipA ressI

FShipCityIMOnsterFLShipCityI FShipPostalCo eI77569FLShipPostalCo eI FShipCountryIPermanyFLShipCountryI FLOr erI... FLOr ersI


SqlXmlCommand$%&ecuteXml"eader T6picall6 6o retrieve (ML res lts *eca se 6o want to wor8 data in an (ML for)at. 9o )ight retrieve data as (ML so that 6o can render o tp t for ) ltiple devicesG 6o )ight want to send (ML data to trading partners in vario s for)atsG or 6o )ight *e e)itting (ML so that it can *e cons )ed *6 an (MLDaware application. 7or these 8inds of scenarios+ 6o sho ld se the %&ecuteXml"eader )ethod+ which ret rns an Xml"eader o*4ect. This is a highDperfor)ance o*4ect that lets 6o iterate thro gh the nodes in the (ML res lt set. 2f 6o need rando) access to the (ML res lts+ 6o can pass Xml"eader as an arg )ent to the constr ctor of an Xml ocument o*4ect. The Xml ocument o*4ect gives 6o f ll >oc )ent 3*4ect Model .>3M1 Level / and Level 2 Core s pport for )anip lating the res lt set. The following sa)ple retrieves the res lts as an Xml"eader o*4ect and passes it to the constr ctor of an Xml ocument o*4ect. 3nce the data is in an Xml ocument o*4ect+ ) ltiple (-ath , eries can e@tract res lts witho t going *ac8 to the data*ase. 2n this case+ prod cts with a nit price greater than 20 are e@tracted.

SqlXmlComman cm ! new SqlXmlComman (Northwin ConnString); cm .,oot-ag!"pro ucts"; cm .Comman -ype ! SqlXmlComman -ype.Sql; cm .Comman -eCt! "S&%&C- D =,OM pro ucts =O, XM% AE-O"; Xm$Reader xr = cmd.ExecuteXm$Reader!"; Xm$+ocument xd = ne Xm$+ocument!";

xd.Load!xr"; Xm$.odeL#st xn$ = xd.Se$ect.odes!"//products0&Un#t-r#ce 1 234""; %oreac5!Xm$.ode xn #n xn$" 6 Conso$e.7r#teL#ne!xn.OuterXm$"; 8


5p to this point+ all the e@a)ples have sed ad hoc , eries to retrieve (ML fro) SQL Server. 9o can also e@ec te stored proced res that ret rn (ML. Consider the following stored proced re!

C,&A-& P,OC&DE,& *o.Pet&mployeesXml AS S&%&C- =irstName3 %astName =,OM employees =O, XM% AE-O ,&-E,N
2n this case+ the 73= (ML A5T3 cla se is part of the S&L&CT state)ent inside the proced re *od6. This state)ent can *e e@ec ted as follows!

SqlXmlComman cm ! new SqlXmlComman (Northwin ConnString); cm .,oot-ag ! "&mployees"; cm .Comman -eCt ! "EXEC 9etEmp$o*eesXML"; Xml,ea er Cr ! cm .&CecuteXml,ea er();
SqlXmlCommand$ClientSideXml 2n )an6 cases+ 6o cannot edit e@isting stored proced res to ret rn an (ML res lt set. 7or e@a)ple+ consider the following stored proced re!

A%-&, P,OC&DE,& *o.Pet&mployees AS S&%&C- =irstName3 %astName =,OM employees ,&-E,N


This is a t6pical stored proced re that does not ret rn (ML. 2n addition+ there are )an6 circ )stances where+ for perfor)ance or other reasons+ 6o want to have the (ML generated on the client rather than directl6 fro) the data*ase. 7or these scenarios+ 6o can se the ClientSideXml propert6 of the SqlXmlCommand o*4ect+ as shown *elow!

SqlXmlComman cm ! new SqlXmlComman (Northwin ConnString);

cm .,oot-ag ! "&mployees"; cmd.C$#entS#deXm$ = true; cm .Comman -eCt ! "EXEC 9etEmp$o*ees FOR XML .ESTE+"; Xml,ea er Cr ! cm .&CecuteXml,ea er(); XmlDocument C ! new XmlDocument(); C .%oa (Cr); Console.Brite%ine(C .OuterXml);
To generate (ML on the client side involves two i)portant steps!

9o ) st set the ClientSideXml propert6 of the SqlXmlCommand o*4ect to true. The Command#e&t propert6 ) st contain either F73= (ML %&ST&>F or F73= (ML =AEF or F73= (ML &@plicitF. This cla se is intercepted *6 the 3L& >; provider+ and indicates that the res lt set sho ld *e converted to (ML.

&ven tho gh the stored proced re has not *een )odified+ 6o end p with an Xml"eader o*4ect on the client. This )echanis) can also *e sed for ad hoc , eries as shown *elow!

cmd.C$#entS#deXm$ = true; cm .Comman -eCt ! "SELECT * FROM products FOR XML .ESTE+"; Xml,ea er Cr ! cm .&CecuteXml,ea er();
Annotated sc+emas 2f 6o are sing ad hoc , eries or stored proced res to , er6 SQL Server 2000+ the col )ns in the res lt set are seriali<ed as attri* ted in the res lting (ML doc )ent. There is also an ele)entD centric )ode for ret rning the (ML sing %&ST&>+ A5T3 or =AE (ML )odes+ 6o can do Select H fro) -rod cts 73= (ML %&ST&>+ &L&M&%TS. 2f 6o want to change the for)at of the ret rned (ML+ 6o can se an annotated sche)a to define which col )ns will *e e@pressed as ele)ents+ and which col )ns will *e e@pressed as attri* tes. Annotated sche)as let 6o f rther )odif6 the res lt set sing standard (-ath. An annotated sche)a is an (ML sche)a doc )ent that specifies *oth the ta*les and col )ns that 6o wish to , er6+ and the str ct re of the res lting (ML. SQL(ML 2.0 s pported two versions of the sche)as+ (ML >ata =ed ced .(>=1 and E3 (ML Sche)a >efinition .(S>1. This sche)a s6nta@ predated the Eorld Eide Ee* Consorti ) .E31 release of a sche)a reco))endation. SQL(ML 3.0 f ll6 s pports the c rrent E3 (ML Sche)a >efinition .(S>1. Consider the following sche)a!

FGCml #ersion!"2.5" enco ing!"utfH6" GI

FCs?schema Cmlns?Cs!"http?LLwww.w<.orgL8552LXM%Schema" Cmlns?sql!"urn?schemasHmicrosoftHcom?mappingHschema"I FCs?element name!"Or er" s:$'re$at#on="Orders"I FCs?compleC-ypeI FCs?sequenceI FCs?element name!"Or erDate" type!"Cs? ate-ime" LI FCs?element name!"ShipName" type!"Cs?string" LI FLCs?sequenceI FCs?attri*ute name!"Or erID" type!"Cs?int" LI FCs?attri*ute name!"CustomerID" type!"Cs?string" LI FCs?attri*ute name!"&mployeeID" type!"Cs?int" LI FLCs?compleC-ypeI FLCs?elementI FLCs?schemaI
This ses the standard E3 sche)a s6nta@ with a single e@ception. The Fs,lF na)espace contains e@tensions that let 6o )ap the co)ponents of the sche)a to specific ta*les and col )ns. 2n this case+ the (ML ele)ent na)es are identical to the data*ase col )n na)es+ so the onl6 specific relationship that needs to *e esta*lished is that of the 3rder ele)ent to the Orders ta*le. This sche)a can *e invo8ed with the following code!

SqlXmlComman cm ! new SqlXmlComman (Northwin ConnString); cm .,oot-ag ! "Or ers"; cmd.CommandText = "Order"; cm .Comman -ype ! SqlXmlComman -ype.XPath; cmd.Sc5ema-at5 = &"..(..(Orders;.xsd"; =ileStream f ! new =ileStream(>"c?@pro ucts.Cml"3=ileMo e.Create); cm .&Cecute-oStream(f); f.Close(); System.Diagnostics.Process.Start(>"c?@pro ucts.Cml");
2n this e@a)ple+ the Sc+emaPat+ propert6 specifies a ph6sical path to a sche)a file. This path is relative to the location of the e@ec ta*le. 2f 6o are sing a Microsoft $is al St dio" .%&T Console application+ and the sche)a is part of 6o r pro4ect+ the sche)a is two directories a*ove the e@ec ta*le .which is in a *inI>e* g or *inI=elease director61. Therefore+ the path incl des F I IF to locate the sche)a relative to the e@ec ta*le. 9o can also se an a*sol te path+ or place the

sche)a in the sa)e ph6sical director6 as the e@ec ta*le+ in which case 6o wo ld 4 st give the file na)e+ 3rders/.@sd. The sche)a file is sed to )ap the res lting (ML to ta*les and col )ns in the data*ase. The Command#e&t propert6 specifies an (-ath , er6 that defines the (ML res lt set. 2n other words+ the sche)a )a6 specif6 that all orders *e ret rned+ * t Command#e&t )a6 li)it the res lt to orders that )atch a specific criterion. 2n the c rrent e@a)ple+ the following (ML is ret rned!

FGCml #ersion!"2.5" enco ing!"utfH6" GI FOr ersI FOr er &mployeeID!"4" CustomerID!"JIN&-" Or erID!"25876"I FOr erDateI2;;KH59H57-55?55?55FLOr erDateI FShipNameIJins et alcools Che#alierFLShipNameI FLOr erI FOr er &mployeeID!"K" CustomerID!"-OMSP" Or erID!"2587;"I FOr erDateI2;;KH59H54-55?55?55FLOr erDateI FShipNameI-oms SpeNialitOtenFLShipNameI FLOr erI ... FLOr ersI
Also notice that the annotated sche)a )a8es it eas6 to ret rn so)e col )ns as ele)ents and other col )ns as attri* tes. !sing ,isual Studio $(%# to generate annotated sc+emas #o use ,isual Studio $(%# to simpli-y t+e process o- generating annotated sc+emas. -ollo) t+ese steps: /. 3pen an e@isting $is al St dio .%&T pro4ect+ and on the Project )en + clic8 Add (e) Item. 2. 3. K. L. M. 2n the Add (e) Item dialog+ in the te)plates pane+ select XML Sc+ema+ and clic8 Open. 3n the ,ie) )en + clic8 Ser/er %&plorer .or press CT=LJALTJS1 to open Server &@plorer. &@pand Ser/ers+ <Machine Name>+ SQL Ser/ers+ <Machine Name>+ (ort+)ind. and #ables. >rag and drop the Products ta*le on to the design s rface. At the lowerDleft corner of the sche)a designer+ clic8 the XML ta*. 9o sho ld see the following code!

9.

FGCml #ersion!"2.5" enco ing!"utfH6" GI

6. ;. 25. 22. 28. 2<. 27. 24. 2K. 29. 26. 2;. 85. 82. 88. 8<. 87. 84. 8K. 89. 86. 8;. <5. <2.

FCs?schema i !"XM%Schema2" targetNamespace!"http?LLtempuri.orgLXM%Schema2.Cs " element=ormDefault!"qualifie " Cmlns!"http?LLtempuri.orgLXM%Schema2.Cs " Cmlns?mstns!"http?LLtempuri.orgLXM%Schema2.Cs " Cmlns?Cs!"http?LLwww.w<.orgL8552LXM%Schema" Cmlns?ms ata!"urn?schemasHmicrosoftHcom?CmlHms ata"I FCs?element name!"Document"I FCs?compleC-ypeI FCs?choice maCOccurs!"un*oun e "I FCs?element name!"Pro ucts"I FCs?compleC-ypeI FCs?sequenceI FCs?element name!"Pro uctID" ms ata?,ea Only!"true" ms ata?AutoIncrement!"true" type!"Cs?int" LI FCs?element name!"Pro uctName" type!"Cs?string" LI FCs?element name!"SupplierID" type!"Cs?int" minOccurs!"5" LI FCs?element name!"CategoryID" type!"Cs?int" minOccurs!"5" LI FCs?element name!"$uantityPerEnit" type!"Cs?string" minOccurs!"5" LI FCs?element name!"EnitPrice" type!"Cs? ecimal" minOccurs!"5" LI

<8. <<. <7. <4. <K. <9. <6. <;. 75. 72. 78. 7<. 77. 74. 7K. 79. 76. 7;.
L0.

FCs?element name!"EnitsInStoc0" type!"Cs?short" minOccurs!"5" LI FCs?element name!"EnitsOnOr er" type!"Cs?short" minOccurs!"5" LI FCs?element name!",eor er%e#el" type!"Cs?short" minOccurs!"5" LI FCs?element name!"Discontinue " type!"Cs?*oolean" LI FLCs?sequenceI FLCs?compleC-ypeI FLCs?elementI FLCs?choiceI FLCs?compleC-ypeI FCs?unique name!"DocumentQey2" ms ata?PrimaryQey!"true"I FCs?selector Cpath!".LLmstns?Pro ucts" LI FCs?fiel Cpath!"mstns?Pro uctID" LI FLCs?uniqueI FLCs?elementI FLCs?schemaI
>elete the te@t shown in *old a*ove. The final sche)a sho ld appear as follows!

42. 48. 4<. 47. 44. 4K.

FGCml #ersion!"2.5" enco ing!"utfH6" GI FCs?schema i !"XM%Schema2" element=ormDefault!"qualifie " Cmlns!"http?LLtempuri.orgLXM%Schema2.Cs " Cmlns?mstns!"http?LLtempuri.orgLXM%Schema2.Cs " Cmlns?Cs!"http?LLwww.w<.orgL8552LXM%Schema" Cmlns?ms ata!"urn?schemasHmicrosoftHcom?CmlHms ata"I

49. 46. 4;. K5. K2. K8. K<. K7. K4. KK. K9. K6. K;. 95. 92. 98. 9<. 97. 94. 9K. 99. 96.

FCs?element name!"Pro ucts"I FCs?compleC-ypeI FCs?sequenceI FCs?element name!"Pro uctID" ms ata?,ea Only!"true" ms ata?AutoIncrement!"true" type!"Cs?int" LI FCs?element name!"Pro uctName" type!"Cs?string" LI FCs?element name!"SupplierID" type!"Cs?int" minOccurs!"5" LI FCs?element name!"CategoryID" type!"Cs?int" minOccurs!"5" LI FCs?element name!"$uantityPerEnit" type!"Cs?string" minOccurs!"5" LI FCs?element name!"EnitPrice" type!"Cs? ecimal" minOccurs!"5" LI FCs?element name!"EnitsInStoc0" type!"Cs?short" minOccurs!"5" LI FCs?element name!"EnitsOnOr er" type!"Cs?short" minOccurs!"5" LI FCs?element name!",eor er%e#el" type!"Cs?short" minOccurs!"5" LI FCs?element name!"Discontinue " type!"Cs?*oolean" LI FLCs?sequenceI FLCs?compleC-ypeI FLCs?elementI FLCs?schemaI

9o can se the following code to , er6 SQL Server sing this sche)a and displa6 the res lts!

SqlXmlComman cm ! new SqlXmlComman (Northwin ConnString);

cm .,oot-ag ! "Pro uct%ist"; cm .Comman -eCt ! "Pro ucts"; cm .Comman -ype ! SqlXmlComman -ype.XPath; cmd.Sc5ema-at5 = &"..(..(XMLSc5ema;.xsd"; =ileStream f ! new =ileStream(>"c?@pro ucts.Cml"3=ileMo e.Create); cm .&Cecute-oStream(f); f.Close(); System.Diagnostics.Process.Start(>"c?@pro ucts.Cml");
As 6o can see+ $is al St dio ta8es )ost of the wor8 o t of a thoring annotated sche)as. Querying )it+ XPat+ The standard (-ath s6nta@ allows 6o to search for )atching ele)ents and li)it a res lt set. (-ath is traditionall6 sed in con4 nction with (SL Transfor)ations .(SLT1 to select certain nodes fro) an inp t (ML doc )ent for transfor)ation or rendering. (-ath is also sed with >3M to select certain nodes to wor8 with progra))aticall6. SQL(ML 3.0 lets 6o se (-ath with annotated sche)as to li)it the res lt set.

Consider the following e@a)ple!

SqlXmlComman cm ! new SqlXmlComman (Northwin ConnString); cm .,oot-ag ! "Or ers"; cmd.CommandText = "Order0S5#pCountr* = <=ra>#$<4"; cmd.CommandT*pe = S:$Xm$CommandT*pe.X-at5; cm .SchemaPath ! >"..@..@Or ersRDetails.Cs "; =ileStream f ! new =ileStream(>"c?@pro ucts.Cml"3=ileMo e.Create); cm .&Cecute-oStream(f); f.Close(); System.Diagnostics.Process.Start(>"c?@pro ucts.Cml");
This e@a)ple retrieves all the orders that were shipped to ;ra<il. This retrieval is done efficientl6 *6 converting the (-ath criteria to a TransactDSQL E'&=& cla se as shown in the following trace!

S&%&C- 2 AS -AP35 AS parent3CONJ&,-(n#archar(7555)3R$2.R-'&S=8328K) AS .Or erT2TOr erDateTelement/3CONJ&,-(n#archar(7555)3R$2.R-'M$P8328K) AS .Or erT2T,equire DateTelement/3CONJ&,-(n#archar(7555)3R$2.R-'=S&8328K) AS

.Or erT2TShippe DateTelement/3R$2.R-'QBC8 AS .Or erT2TShipJiaTelement/3R$2.R-''<=8 AS .Or erT2T=reightTelement/3R$2.R-'P%S2 AS .Or erT2TShipNameTelement/3R$2.R-'PSD8 AS .Or erT2TShipA ressTelement/3R$2.R-'C4C8 AS

.Or erT2TShipCityTelement/3R$2.R-'C,EB AS .Or erT2TShip,egionTelement/3R$2.R-'O,D8 AS .Or erT2TShipPostalCo eTelement/3R$2.R-'N&S2 AS .Or erT2TShipCountryTelement/3R$2.A5 AS .Or erT2T&mployeeID/3R$2.A2 AS .Or erT2TCustomerID/3R$2.A8 AS .Or erT2TOr erID/ from (S&%&CR$'5.&mployeeID AS A53R$'5.CustomerID AS A23R$'5.Or erID AS A83R$'5.Or erID AS R-'PMU83R$'5.CustomerID AS R-'M,=83R$'5.&mployeeID AS R-'UX&83R$'5.ShipCountry AS R-'N&S23R$'5.ShipPostalCo e AS R-'O,D83R$'5.Ship,egion AS R-'C,EB3R$'5.ShipCity AS R-'C4C83R$'5.ShipA ress AS R-'PSD83R$'5.ShipName AS R-'P%S23

R$'5.=reight AS R-''<=83R$'5.ShipJia AS R-'QBC83R$'5.Shippe Date AS R-'=S&83R$'5.,equire Date AS R-'M$P83R$'5.Or erDate AS R-'&S=8 from Or ers R$'5) R$2 7?ERE CONJ&,-(n#archar(7555)3R$2.R-'N&S2328K) IS NO- NE%% AND (CONJ&,-(n#archar(7555)3R$2.R-'N&S2328K) ! NV=ra>#$V) =O, XM% &XP%ICI-3 'INA,W 'AS&K7
The details of this S&L&CT state)ent are *e6ond the scope of this paper+ * t notice that the E'&=& cla se li)its the res lt set to orders fro) ;ra<il+ rather than ret rning all the orders *efore filtering. Querying )it+ template -iles SQL(ML s pports e@posing SQL Server 2000 directl6 to the Ee* sing te)plate files that define the , er6 and para)eters. These are (ML files that are placed in a virt al root and are accessi*le thro gh 'TT-. 9o can+ however+ e@ec te these te)plate files directl6 sing SQL(ML Managed Classes. 9o set the Command#e&t propert6 of the SqlXmlConnection to contain the path to the (ML te)plate file+ and then 6o set the Command#ype propert6 to FS,l()lCo))andT6pe.Te)plate7ileF. The following e@a)ple te)plate ass )es that 6o have saved the te)plate as prod cts.@)l!

FGCml #ersion!"2.5" enco ing!"utfH6" GI FPro ucts Cmlns?sql!"urn?schemasHmicrosoftHcom?CmlHsql"I

Fsql?queryI S&%&C- Pro ucts.Pro uctID3 Pro ucts.Pro uctName3 Suppliers.CompanyName AS SupplierName3 Categories.CategoryName3 Pro ucts.$uantityPerEnit3 Pro ucts.EnitPrice3 Pro ucts.EnitsInStoc03 Pro ucts.EnitsOnOr er3 Pro ucts.,eor er%e#el3 Pro ucts.Discontinue =,OM Pro ucts INN&, XOIN Suppliers ON Pro ucts.SupplierID ! Suppliers.SupplierID INN&, XOIN Categories ON Pro ucts.CategoryID ! Categories.CategoryID =O, XM% ,AB FLsql?queryI FLPro uctsI
9o can then se the following section of code to e@ec te this te)plate and displa6 the res lts!

SqlXmlComman cm ! new SqlXmlComman (Northwin ConnString); cm .,oot-ag ! "Pro ucts"; cmd.CommandText = &"..(..(-roducts.xm$"; cmd.CommandT*pe = S:$Xm$CommandT*pe.Temp$ateF#$e; =ileStream f ! new =ileStream(>"c?@pro ucts.Cml"3=ileMo e.Create); cm .&Cecute-oStream(f); f.Close(); System.Diagnostics.Process.Start(>"c?@pro ucts.Cml");
Aut+oring templates using ,isual Studio $(%# Query 0uilder Altho gh $is al St dio .%&T doesnNt directl6 s pport a thoring (ML te)plates+ 6o can get )ost of the wor8 done sing Q er6 ; ilder+ as o tlined in the following steps! /. Eith a pro4ect open in $is al St dio .%&T+ on the Project )en + clic8 Add (e) Item .or press CT=LJS'27TJA1. 2. 3. 2n the Add (e) Item dialog+ in the te)plates pane+ select XML 'ile. 2n the (ame field+ enter orders$&ml+ and clic8 Open.

K.

Add the following code to the file!

4. K. 9. 6.
0. /0. //. /2. /3. /K. /L. /M. /7. /O.

FPro ucts Cmlns?sql!"urn?schemasHmicrosoftHcom?CmlHsql"I Fsql?queryI FLsql?queryI FLPro uctsI


3n the ,ie) )en + clic8 Ser/er %&plorer .or press CT=LJALTJS1 to open Server &@plorer. &@pand Ser/ers+ <Machine Name>+ SQL Ser/ers+ <Machine Name>+ and (ort+)ind. =ightDclic8 ,ie)s and then clic8 (e) ,ie). The Q er6 ; ilder tilit6 opens. 2n the Add #able dialog+ do *leDclic8 the following ta*les! Orders+ Order Products+ %mployees+ and Customers. Clic8 Close. 2n the diagra) pane+ in the Orders ta*le+ select the following col )ns! OrderI + Order ate+ "equired ate+ and S+ipped ate. 2n the Order iscount. 2n the %mployees ta*le+ select the following col )ns! 'irst(ame and Last(ame. 2n the Customers ta*le+ select the following col )n! Company(ame. 2n the Products ta*le+ select the following col )n! Product(ame. Select ever6thing in the SQL pane .SELECT dbo. rders. rder!"P1+ and press CT=LJC to cop6 the selection to the Clip*oard. etails ta*le+ select the following col )ns! !nitPrice+ Quantity+ and etails+

19.
20. 2/.

Close Q er6 ; ilder. Ehen pro)pted to save changes+ clic8 (o. 2n orders$&ml+ place the insertion point *etween #s$l%$&ery' and #(s$l%$&ery'. -ress CT=LJ$ to paste the Clip*oard contents into the SQL field. Q st *efore #(s$l%$&ery'+ t6pe )F R *+L R,W). -ress %(#%". The file sho ld appear as follows!

22.
23.

24.
84. 8K. 89. 86. 8;. <5. <2.

FGCml #ersion!"2.5" enco ing!"utfH6" GI FPro ucts Cmlns?sql!"urn?schemasHmicrosoftHcom?CmlHsql"I Fsql?queryI S&%&C- *o.Or ers.Or erID3 *o.Or ers.Or erDate3 *o.Or ers.,equire Date3 *o.Or ers.Shippe Date3 *o..Or er Details/.EnitPrice3 *o..Or er Details/.$uantity3 *o..Or er Details/.Discount3

<8. <<. <7. <4. <K. <9. <6. <;. 75. 72. 78. 7<. 77. 74. 7K. 79. 76.
K0.

*o.&mployees.%astName3 *o.&mployees.=irstName3 *o.Customers.CompanyName3 *o.Pro ucts.Pro uctName =,OM *o.Or ers INN&, XOIN *o..Or er Details/ ON *o.Or ers.Or erID ! *o..Or er Details/.Or erID INN&, XOIN *o.&mployees ON *o.Or ers.&mployeeID ! *o.&mployees.&mployeeID INN&, XOIN *o.Customers ON *o.Or ers.CustomerID ! *o.Customers.CustomerID INN&, XOIN *o.Pro ucts ON *o..Or er Details/.Pro uctID ! *o.Pro ucts.Pro uctID =O, XM% ,AB FLsql?queryI FLPro uctsI
9o can test this te)plate with the following code!

45. 42. 48. 4<. 47. 44. 4K.

SqlXmlComman cm ! new SqlXmlComman (Northwin ConnString); cm .,oot-ag ! "Or ers"; cm .Comman -eCt ! >"..@..@or ers.Cml"; cm .Comman -ype ! SqlXmlComman -ype.-emplate=ile; =ileStream f ! new =ileStream(>"c?@or ers.Cml"3=ileMo e.Create); cm .&Cecute-oStream(f); f.Close();

49.

System.Diagnostics.Process.Start(>"c?@or ers.Cml");

SqlXmlParameter
5p to this point+ all the , eries+ stored proced res+ sche)as+ (-ath e@pressions+ and te)plates have *een static. 3ften+ however+ 6o want to )odif6 the , er6 *ased on so)e criteria. 7or e@a)ple+ 6o 8now that 6o want to select orders *6 c sto)er+ * t it isnNt ntil r n ti)e that 6o 8now the specific c sto)ers whose orders 6o want to see. To )a8e these , eries d6na)ic+ 6o can para)eteri<e the) and se the SqlXmlParameter o*4ect to specif6 val es for the para)eters at r n ti)e. Parameteri1ed ad +oc queries 7or an ad hoc , er6+ si)pl6 se a FRF to indicate that the val e is s pplied *6 a para)eter+ as shown in the following e@a)ple!

SqlXmlComman cm ! new SqlXmlComman (Northwin ConnString); cm .,oot-ag!"pro ucts"; cm .Comman -ype ! SqlXmlComman -ype.Sql; cmd.CommandText= "SELECT * FROM products 7?ERE cate,or*#d = @ " A "FOR XML AUTO"; S:$Xm$-arameter p = cmd.Create-arameter!"; p.Ba$ue = ";"; Xml,ea er Cr ! cm .&CecuteXml,ea er(); XmlDocument C ! new XmlDocument(); C .%oa (Cr); Console.Brite%ine(C .OuterXml);
Stored procedure parameters The )odel for passing para)eters to stored proced res is ver6 si)ilar to the )odel for para)eteri<ed ad hoc , eries. 9o se a FRF for each arg )ent passed to the proced re+ and se SqlXmlParameter to assign a val e. 2f the stored proced re does not e)it (ML .*6 internall6 sing 73= (ML =AE+ 73= (ML A5T3+ or 73= (ML &(-L2C2T )+ 6o ) st se clientDside (ML+ as ill strated *elow!

SqlXmlComman cm ! new SqlXmlComman (Northwin ConnString); cm .,oot-ag ! "Or ers"; cmd.C$#entS#deXm$ = true; cmd.CommandText = "EXEC 9etOrders @ FOR XML .ESTE+"; S:$Xm$-arameter p = cmd.Create-arameter!";

p.Ba$ue = "a$%C#"; Xml,ea er Cr ! cm .&CecuteXml,ea er(); XmlDocument C ! new XmlDocument(); C .%oa (Cr); Console.Brite%ine(C .OuterXml);
(ote 7or ad hoc , eries and stored proced res+ 6o can se positional para)eters as shown a*ove+ * t 6o cannot se na)ed para)eters+ as 6o can with (-ath and (ML te)plates+ which are disc ssed *elow. XPat+ parameters 9o can also para)eteri<e (-ath , eries. 9o se the standard (-ath varia*le s6nta@ to denote the position of the para)eter in the , er6G 6o then can se positional or na)ed para)eters to specif6 the val es. 2n the following e@a)ple+ the Command#e&t propert6 contains an (-ath state)ent that selects all the order details for a specific prod ct 2>. The prod ct 2> is specified *6 an (-ath varia*le called -.rod&/t!" .-VariableName is the standard (-ath s6nta@ for a varia*le1. 9o can set the val e for this varia*le sing the SqlXmlParameter class+ as shown *elow!

SqlXmlComman cm ! new SqlXmlComman (Northwin ConnString); cm .,oot-ag ! "Or ers"; cm .Comman -eCt ! "Or erLOr erDetails.Pro uctID ! YPro uctID/"; cm .Comman -ype ! SqlXmlComman -ype.XPath; cm .SchemaPath ! >"..@..@Or ersRDetails.Cs "; S:$Xm$-arameter p = cmd.Create-arameter!"; p..ame = "&-roductD+"; p.Ba$ue = ";"; =ileStream f ! new =ileStream(>"c?@pro ucts.Cml"3=ileMo e.Create); cm .&Cecute-oStream(f); f.Close(); System.Diagnostics.Process.Start(>"c?@pro ucts.Cml");
#emplate parameters 2t is also possi*le to pass para)eters to (ML te)plate files. 7irst+ the te)plate file ) st *e written to accept para)eters. -ara)eters are specified in the header section of the (ML te)plate+ as in the following e@a)ple!

FGCml #ersion!"2.5" enco ing!"utfH6" GI F,OO- Cmlns?sql!Vurn?schemasHmicrosoftHcom?CmlHsqlVI

Es:$'5eader 1 Es:$'param name=<Cate,or*D+<1E/s:$'param1 E/s:$'5eader1 Fsql?query I S&%&C- D =,OM Pro ucts BU&,& CategoryID ! >CategoryID =O, XM% AE-O FLsql?queryI FL,OO-I
The val e for Category!" can then *e specified sing the SqlXmlParameter o*4ect+ as follows!

SqlXmlComman cm ! new SqlXmlComman (Northwin ConnString); cm .,oot-ag ! "Or ers"; cm .Comman -eCt ! >"..@..@pro ucts8.Cml"; cm .Comman -ype ! SqlXmlComman -ype.-emplate=ile; S:$Xm$-arameter p = cmd.Create-arameter!"; p..ame = "&Cate,or*D+"; p.Ba$ue = "F"; =ileStream f ! new =ileStream(>"c?@or ers.Cml"3=ileMo e.Create); cm .&Cecute-oStream(f); f.Close(); System.Diagnostics.Process.Start(>"c?@or ers.Cml");
SqlXmlAdapter
The SqlXmlAdapter o*4ect can *e sed to pdate the data*ase with an (ML >iff?ra). This is sef l if 6o have generated (ML data sing an annotated sche)a+ the ser has )odified the data+ and 6o wish to store the changes *ac8 in the data*ase. >iff?ra)s s pport insert+ pdate+ and delete operations. The SqlXmlAdapter o*4ect contains two )ethods+ which are descri*ed in the following ta*le. Met+od 'ill2DataSet ds3 escription -op lates a ataSet o*4ect with (ML data retrieved fro) SQL Server. 5pdates SQL Server to reflect changes to the ataSet o*4ect sing an (ML >iff?ra).

!pdate2DataSet ds3

7or e@a)ple+ ass )e that 6o have created the following sche)a!

FGCml #ersion!"2.5" enco ing!"utfH6" GI FCs?schema Cmlns?Cs!"http?LLwww.w<.orgL8552LXM%Schema" Cmlns?sql!"urn?schemasHmicrosoftHcom?mappingHschema"I FCs?element name!"Categories"I FCs?compleC-ypeI FCs?sequenceI FCs?element name!"CategoryID" type!"Cs?integer"LI FCs?element name!"CategoryName" type!"Cs?string"LI FLCs?sequenceI FLCs?compleC-ypeI FLCs?elementI FLCs?schemaI
9o can se this sche)a in co)*ination with SqlXmlAdapter to pop late a pdate the data*ase with changes+ as shown *elow! ataSet o*4ect and

SqlXmlComman cm ! new SqlXmlComman (Northwin ConnString); cm .,oot-ag ! ",OO-"; cm .Comman -eCt ! "Categories"; cm .Comman -ype ! SqlXmlComman -ype.XPath; cmd.Sc5ema-at5 = &"..(..(Cate,or#es.xsd"; DataSet s ! new DataSet(); S:$Xm$Adapter ad = ne ad.F#$$!ds"; ds.TaG$es0"Cate,or#es"4.Ro s0340"Cate,or*.ame"4 = "+r#nCs"; ad.Update!ds";
This e@a)ple pop lates a ataSet o*4ect sing an annotated sche)a. A cell in the ataSet o*4ect is changed+ and the changes are p shed *ac8 to the data*ase sing the !pdate )ethod of the SqlXmlAdapter o*4ect.

S:$Xm$Adapter!cmd";

Conclusion
SQL(ML Managed Classes let 6o a thor .%&T code that ta8es advantage of the feat res previo sl6 provided *6 SQL(ML. These feat res incl de the a*ilit6 to generate (ML on the server or client side sing the following )echanis)s! ad hoc , eries+ stored proced res+ annotated sche)as and (-ath+ and (ML te)plates.

About t+e Aut+or


Scott Swigart is a senior principal of 3 Leaf Sol tions+ a co)pan6 that speciali<es in training and cons lting services for earl6 adopters of Microsoft technologies. 2n this role+ Scott has provided training and cons lting to Microsoft Cons lting Services and other corporations since the ;eta / release of Microsoft .%&T. 9o can find )ore infor)ation a*o t Scott Swigart and 3 Leaf Sol tions at www.3leaf.co) A http!BBwww.3leaf.co)B C .

Microsoft Corporation. All rights reserved. A http!BB)sdn2.)icrosoft.co)BenD sBli*rar6B)s3M0OM3.printer1.asp@ C

You might also like