2/23/05 cs-561 - advanced databases 1 xml support in sql server 2000 sriram krishnan kevin menard
TRANSCRIPT
2/23/05 CS-561 - Advanced Databases 1
XML Support in XML Support in SQL Server 2000SQL Server 2000
Sriram Krishnan
Kevin Menard
2/23/05 2CS-561 - Advanced Databases
SQL Server - XMLSQL Server - XML
SQL Server 2000 is an XML-enabled SQL Server 2000 is an XML-enabled DBMS:DBMS: It can read and write XML dataIt can read and write XML data It can return data from databases in It can return data from databases in
XML formatXML format It can read and update data stored in It can read and update data stored in
XML documentsXML documents
2/23/05 3CS-561 - Advanced Databases
SQL Server's XML SQL Server's XML FeaturesFeatures
FOR XMLFOR XML An extension to An extension to
SELECTSELECT - allows - allows result sets as XMLresult sets as XML
OpenXMLOpenXML Allows reading and Allows reading and
writing of data in writing of data in XML documentsXML documents
XPath queriesXPath queries Allows SQL Server Allows SQL Server
databases to be databases to be queried using XPath queried using XPath syntaxsyntax
SchemasSchemas Supports XDR Supports XDR
mapping schema and mapping schema and XPath queries XPath queries against themagainst them
UpdategramsUpdategrams XML templates for XML templates for
data modificationsdata modifications
XML Bulk LoadXML Bulk Load A high-speed facility A high-speed facility
for loading XML data for loading XML data into a SQL Serverinto a SQL Server
2/23/05 4CS-561 - Advanced Databases
SELECT … FOR XML SELECT … FOR XML
FOR XMLFOR XML causes causes SELECTSELECT to return to return query results as an XML streamquery results as an XML stream
Three formats: RAW, AUTO, or Three formats: RAW, AUTO, or EXPLICIT EXPLICIT SELECT column list FROM table list WHERE SELECT column list FROM table list WHERE
filter criteria FOR XML RAW | AUTO | filter criteria FOR XML RAW | AUTO | EXPLICIT [, XMLDATA] [, ELEMENTS] [, EXPLICIT [, XMLDATA] [, ELEMENTS] [, BINARY BASE64]BINARY BASE64]
2/23/05 5CS-561 - Advanced Databases
FOR XML -- Raw ModeFOR XML -- Raw Mode SELECT CustomerId, CompanyName SELECT CustomerId, CompanyName
FROM Customers FOR XML RAW:FROM Customers FOR XML RAW:
XML_F52E2B61-18A1-11d1-B105-00805F49916BXML_F52E2B61-18A1-11d1-B105-00805F49916B------------------------------------------------------------------ ------------------------------------------------------------------ <row CustomerId="ALFKI" CompanyName="Alfreds Futterkiste"/><row CustomerId="ALFKI" CompanyName="Alfreds Futterkiste"/><row CustomerId="ALMRT" CompanyName="Antonio Moreno Taquer'a"/><row CustomerId="ALMRT" CompanyName="Antonio Moreno Taquer'a"/><row CustomerId="BERGS" CompanyName="Berglunds snabbköp"/><row CustomerId="BERGS" CompanyName="Berglunds snabbköp"/>
Columns Columns Attributes Attributes Rows Rows Generic “row element” Generic “row element” XML returned is not well-formed XML returned is not well-formed
Lacks a root element – must be generated by Lacks a root element – must be generated by the clientthe client
2/23/05 6CS-561 - Advanced Databases
FOR XML -- Auto ModeFOR XML -- Auto Mode SELECT CustomerId, CompanyName FROM Customers FOR XML SELECT CustomerId, CompanyName FROM Customers FOR XML
AUTOAUTO
XML_F52E2B61-18A1-11d1-B105-00805F49916BXML_F52E2B61-18A1-11d1-B105-00805F49916B------------------------------------------------------------------ ------------------------------------------------------------------ <Customers <Customers CustomerId="ALFKI" CompanyName="Alfreds Futterkiste"/>CustomerId="ALFKI" CompanyName="Alfreds Futterkiste"/> <Customers <Customers CustomerId= "ALMRT" CompanyName="Antonio Moreno Taquer'a"/>CustomerId= "ALMRT" CompanyName="Antonio Moreno Taquer'a"/> <Customers <Customers CustomerId="BERGS" CompanyName="Berglunds snabbköp"/>CustomerId="BERGS" CompanyName="Berglunds snabbköp"/>
Each row in the result set is named after the Each row in the result set is named after the table or viewtable or view
For results with more than one row, this amounts For results with more than one row, this amounts to having more than one top-level (root) element to having more than one top-level (root) element in the fragment, which isn't allowed in XMLin the fragment, which isn't allowed in XML
The rows from joined tables are nested within The rows from joined tables are nested within one another.one another.
2/23/05 7CS-561 - Advanced Databases
FOR XML -- Auto Mode FOR XML -- Auto Mode (cont.)(cont.)
Example of a JOIN query:Example of a JOIN query:
SELECT Customers.CustomerID, CompanyName, OrderId FROM SELECT Customers.CustomerID, CompanyName, OrderId FROM Customers JOIN Orders ON Customers JOIN Orders ON (Customers.CustomerId=Orders.CustomerId) FOR XML AUTO (Customers.CustomerId=Orders.CustomerId) FOR XML AUTO
XML_F52E2B61-18A1-11d1-B105-00805F49916B XML_F52E2B61-18A1-11d1-B105-00805F49916B ------------------------------------------------------------------ ------------------------------------------------------------------ <Customers CustomerID="ALFKI" CompanyName="Alfreds Futterkiste"> <Customers CustomerID="ALFKI" CompanyName="Alfreds Futterkiste">
<Orders OrderId="10643"/><Orders OrderId="10643"/><Orders OrderId="10702"/><Orders OrderId="10702"/><Orders OrderId="10952"/><Orders OrderId="10952"/>
</Customers> </Customers> <Customers CustomerID="ANATR" CompanyName="Ana Trujillo Emparedado <Customers CustomerID="ANATR" CompanyName="Ana Trujillo Emparedado <Orders OrderId="10308"/><Orders OrderId="10308"/>
<Orders OrderId="10759"/><Orders OrderId="10759"/></Customers> </Customers> <Customers CustomerID="FRANR" CompanyName="France restauration"> <Customers CustomerID="FRANR" CompanyName="France restauration">
<Orders OrderId="10671"/><Orders OrderId="10671"/><Orders OrderId="10971"/> <Orders OrderId="10971"/>
</Customers> </Customers>
2/23/05 8CS-561 - Advanced Databases
FOR XML – Explicit ModeFOR XML – Explicit Mode More flexible and more complicated than More flexible and more complicated than
either raw mode or auto mode either raw mode or auto mode Explicit mode queries define XML Explicit mode queries define XML
documents in terms of a “universal table documents in terms of a “universal table format”format” A mechanism for describing the format of XML A mechanism for describing the format of XML
document returneddocument returned A universal table is just a SQL Server result set A universal table is just a SQL Server result set
with special column headings that tell the with special column headings that tell the server how to produce an XML document from server how to produce an XML document from your datayour data
Element!Tag!Attribute!Directive Element!Tag!Attribute!Directive
2/23/05 9CS-561 - Advanced Databases
Universal Table FormatUniversal Table FormatTag Parent Customers!1!CustomerId Customers!1 Orders!2!OrderId Orders!2!OrderDate!elementTag Parent Customers!1!CustomerId Customers!1 Orders!2!OrderId Orders!2!OrderDate!element----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 NULL ALFKI Alfreds Futterkiste NULL NULL1 NULL ALFKI Alfreds Futterkiste NULL NULL2 1 ALFKI NULL 10643 1997-08-25T00:00:00 2 1 ALFKI NULL 10643 1997-08-25T00:00:00 2 1 ALFKI NULL 10692 1997-10-03T00:00:002 1 ALFKI NULL 10692 1997-10-03T00:00:001 NULL ANATR Ana Trujillo Empare NULL NULL1 NULL ANATR Ana Trujillo Empare NULL NULL2 1 ANATR NULL 10308 1996-09-18T00:00:002 1 ANATR NULL 10308 1996-09-18T00:00:00
2/23/05 10CS-561 - Advanced Databases
Explicit Mode – Complex Explicit Mode – Complex QueryQuery
Links the Customers and Orders tables using the CustomerId Links the Customers and Orders tables using the CustomerId columncolumn
The Tag and Parent values in the second query link it to the first The Tag and Parent values in the second query link it to the first
SELECT 1 AS Tag, NULL AS Parent, CustomerId AS [Customers!1!CustomerId], SELECT 1 AS Tag, NULL AS Parent, CustomerId AS [Customers!1!CustomerId], CompanyName AS [Customers!1], NULL AS [Orders!2!OrderId], NULL AS [Orders!2!CompanyName AS [Customers!1], NULL AS [Orders!2!OrderId], NULL AS [Orders!2!OrderDate!element] FROM Customers UNION OrderDate!element] FROM Customers UNION
SELECT 2 AS Tag, 1 AS Parent, CustomerId, NULL, OrderId, OrderDate FROM Orders SELECT 2 AS Tag, 1 AS Parent, CustomerId, NULL, OrderId, OrderDate FROM Orders ORDER BY [Customers!1!CustomerId], [Orders!2!OrderDate!element] FOR XML ORDER BY [Customers!1!CustomerId], [Orders!2!OrderDate!element] FOR XML EXPLICITEXPLICIT
XML_F52E2B61-18A1-11d1-B105-00805F49916B XML_F52E2B61-18A1-11d1-B105-00805F49916B ------------------------------------------------------------------ ------------------------------------------------------------------ <Customers CustomerId="ALFKI">Alfreds Futterkiste <Customers CustomerId="ALFKI">Alfreds Futterkiste
<Orders OrderId="10643"> <Orders OrderId="10643"> <OrderDate>1997-08-25T00:00:00</OrderDate> <OrderDate>1997-08-25T00:00:00</OrderDate>
</Orders> </Orders> <Orders OrderId="10692"> <Orders OrderId="10692">
<OrderDate>1997-10-03T00:00:00</OrderDate> <OrderDate>1997-10-03T00:00:00</OrderDate> </Orders> </Orders>
</Customers> </Customers> <Customers CustomerId="ANATR">Ana Trujillo Emparedados y helados <Customers CustomerId="ANATR">Ana Trujillo Emparedados y helados
<Orders OrderId="10308"> <Orders OrderId="10308"> <OrderDate>1996-09-18T00:00:00</OrderDate> <OrderDate>1996-09-18T00:00:00</OrderDate>
</Orders> </Orders> </Customers> </Customers>
2/23/05 11CS-561 - Advanced Databases
OpenXMLOpenXML OpenXML is a built-in Transact-SQL OpenXML is a built-in Transact-SQL
function that can return an XML function that can return an XML document as a rowsetdocument as a rowset
Syntax:Syntax: OpenXML(hdoc, RowPattern [, Flag] OpenXML(hdoc, RowPattern [, Flag]
[WITH SchemaDeclaration | [WITH SchemaDeclaration | TableName]TableName]
hdoc = Handle to XML Documenthdoc = Handle to XML Document Returned from sp_xml_preparedocumentReturned from sp_xml_preparedocument
RowPattern = XPath expression that identifies rowsRowPattern = XPath expression that identifies rows Flag = Attribute or element-centric column patternsFlag = Attribute or element-centric column patterns WITH = Shredded rowset based upon additional parameters WITH = Shredded rowset based upon additional parameters
(omission of WITH = edge table view)(omission of WITH = edge table view)
2/23/05 12CS-561 - Advanced Databases
OpenXML ExampleOpenXML ExampleDECLARE @hDoc int EXEC sp_xml_preparedocument DECLARE @hDoc int EXEC sp_xml_preparedocument @hDoc output, @hDoc output, '<songs> '<songs> <artist name="Johnny Hartman"> <artist name="Johnny Hartman">
<song> <name>It Was Almost Like a Song</name></song><song> <name>It Was Almost Like a Song</name></song> <song> <name>I See Your Face Before Me</name></song><song> <name>I See Your Face Before Me</name></song> <song> <name>Easy Living</name></song> <song> <name>Easy Living</name></song>
</artist> </artist> <artist name="Harry Connick, Jr."> <artist name="Harry Connick, Jr."> <song> <name>Sonny Cried</name></song> <song> <name>Sonny Cried</name></song>
<song> <name>A Nightingale Sang</name></song> <song> <name>A Nightingale Sang</name></song> <song> <name>You Didn't Know Me When</name></song><song> <name>You Didn't Know Me When</name></song>
</artist> </artist> </songs>' </songs>' SELECT * FROM OPENXML(@hdoc, '/songs/artist/song', 2) WITH SELECT * FROM OPENXML(@hdoc, '/songs/artist/song', 2) WITH (artist varchar(30) '../@name', (artist varchar(30) '../@name', song varchar(50) 'name') song varchar(50) 'name') EXEC sp_xml_removedocument @hDocEXEC sp_xml_removedocument @hDoc
artist artist song song --------------------------- --------------------------------------------------------------- ------------------------------------Johnny Hartman Johnny Hartman It Was Almost Like a Song It Was Almost Like a Song Johnny Hartman Johnny Hartman I See Your Face Before Me I See Your Face Before Me Johnny Hartman Johnny Hartman Easy Living Easy Living Harry Connick Jr. Harry Connick Jr. Sonny Cried Sonny Cried Harry Connick Jr. Harry Connick Jr. A Nightingale Sang, A Nightingale Sang, Harry Connick Jr. Harry Connick Jr. You Didn't Know Me When You Didn't Know Me When
2/23/05 13CS-561 - Advanced Databases
XML Mapping SchemaXML Mapping Schema XML schemas are XML documents that define the XML schemas are XML documents that define the
type of data that other XML documents may type of data that other XML documents may containcontain Replacement for DTDReplacement for DTD
A mapping schema is a special type of schema A mapping schema is a special type of schema that maps data between an XML document and a that maps data between an XML document and a relational table relational table Can be used to create an XML view of a SQL Server table Can be used to create an XML view of a SQL Server table
SQL Server's XML schema support is based on SQL Server's XML schema support is based on XML-Data Reduced (XDR) XML-Data Reduced (XDR) An XML-Data subset that can be used to define schemasAn XML-Data subset that can be used to define schemas
2/23/05 14CS-561 - Advanced Databases
Annotated Mapping Annotated Mapping SchemaSchema
An annotated schema is a mapping schema An annotated schema is a mapping schema with special annotations (from the XML-with special annotations (from the XML-SQL namespace) that link elements and SQL namespace) that link elements and attributes with tables and columnsattributes with tables and columns Table Table element (default) element (default) Column Column attribute (default) attribute (default)
Provides same level of granularity as FOR Provides same level of granularity as FOR … XML EXPLICIT, without having to use … XML EXPLICIT, without having to use universal tablesuniversal tables
2/23/05 15CS-561 - Advanced Databases
Annotated Mapping Annotated Mapping Schema (cont.)Schema (cont.)
Example Schema:Example Schema:
<?xml version="1.0"?> <?xml version="1.0"?> <Schema name="customers" xmlns="urn:schemas-<Schema name="customers" xmlns="urn:schemas-
microsoft-com:xml-data" xmlns:sql="urn:schemas-microsoft-com:xml-data" xmlns:sql="urn:schemas-microsoft-com:xml-sql">microsoft-com:xml-sql">
<ElementType name="Customer“ <ElementType name="Customer“ sql:relation="Customers"> sql:relation="Customers">
<AttributeType name="CustomerNumber“ <AttributeType name="CustomerNumber“ sql:field="CustomerId"/>sql:field="CustomerId"/>
<AttributeType name="Name" sql:field="CompanyName"/><AttributeType name="Name" sql:field="CompanyName"/></ElementType> </ElementType> </Schema></Schema>
2/23/05 16CS-561 - Advanced Databases
Querying Using XPathQuerying Using XPath
XPath is a tree navigation language defined XPath is a tree navigation language defined by W3Cby W3C
SQL Server uses XPath to select data from SQL Server uses XPath to select data from XML views provided by annoted schemaXML views provided by annoted schema http://localhost/Northwind/Schema/http://localhost/Northwind/Schema/Customer.XDR/Customer[@Id=A%25]Customer.XDR/Customer[@Id=A%25]
XPath query can be passed via URL or XPath query can be passed via URL or template or via SQLOLEDB providertemplate or via SQLOLEDB provider
2/23/05 17CS-561 - Advanced Databases
UpdategramsUpdategrams
Updategrams provide an XML-based Updategrams provide an XML-based method to update databasemethod to update database Templates with special attributes and Templates with special attributes and
elementselements Specify the data to update, how to update itSpecify the data to update, how to update it All the execution mechanisms available with All the execution mechanisms available with
templates work equally well with templates work equally well with updategrams updategrams
POST, save to file and execute via URL, via ADOPOST, save to file and execute via URL, via ADO
2/23/05 18CS-561 - Advanced Databases
Updategrams (cont.)Updategrams (cont.)
Each updategram:Each updategram: Contains the data changes in the form Contains the data changes in the form
of before and after elements.of before and after elements. Before element contains the before Before element contains the before
image of the data to be changedimage of the data to be changed Row deletionsRow deletions
Have before image but no after image Have before image but no after image Row InsertionsRow Insertions
Have an after image but no before Have an after image but no before image image
2/23/05 19CS-561 - Advanced Databases
Updategrams (cont.)Updategrams (cont.)<?xml version="1.0"?> <?xml version="1.0"?> <employeeupdate <employeeupdate xmlns:updg= "urn:schemas-microsoft-com:xml-updategramxmlns:updg= "urn:schemas-microsoft-com:xml-updategram"> "> <updg:sync> <updg:sync>
<updg:before> <updg:before> <Employees EmployeeID="4"/> <Employees EmployeeID="4"/>
</updg:before> </updg:before> <updg:after> <updg:after>
<Employees City="Scotts Valley" Region="CA"/> </updg:after> <Employees City="Scotts Valley" Region="CA"/> </updg:after> </updg:sync> </updg:sync> </employeeupdate></employeeupdate>
Updategrams can also be parameterized:Updategrams can also be parameterized:
<updg:header> <updg:header> <updg:param name="OrderID"/> <updg:param name="OrderID"/> <updg:param name="ShipCity"/><updg:param name="ShipCity"/>
</updg:header> </updg:header>
2/23/05 20CS-561 - Advanced Databases
Updategrams (cont.)Updategrams (cont.) Updategrams can also use XDR mapping Updategrams can also use XDR mapping
schemas:schemas:
<?xml version="1.0"?> <?xml version="1.0"?> <orderupdate xmlns:updg= "urn:schemas-microsoft-com:xml-updategram"> <orderupdate xmlns:updg= "urn:schemas-microsoft-com:xml-updategram"> <updg:sync <updg:sync updg:mapping-schema="OrderSchema.xml"updg:mapping-schema="OrderSchema.xml">><updg:before> <Order OID="10248"/> </updg:before><updg:before> <Order OID="10248"/> </updg:before><updg:after> <Order City="Reims"/> </updg:after><updg:after> <Order City="Reims"/> </updg:after></updg:sync> </orderupdate> </updg:sync> </orderupdate>
Where the XDR schema is given by:Where the XDR schema is given by:
<?xml version="1.0"?> <?xml version="1.0"?> <Schema xmlns="urn:schemas-microsoft-com:xml-data" <Schema xmlns="urn:schemas-microsoft-com:xml-data"
xmlns:sql="urn:schemas-microsoft-com:xml-sql">xmlns:sql="urn:schemas-microsoft-com:xml-sql"><ElementType name="Order" sql:relation="Orders"><ElementType name="Order" sql:relation="Orders"> <AttributeType name="OID"/> <AttributeType name="City"/><AttributeType name="OID"/> <AttributeType name="City"/> <attribute type="OID" sql:field="OrderID"/> <attribute type="OID" sql:field="OrderID"/> <attribute type="City" sql:field="ShipCity"/><attribute type="City" sql:field="ShipCity"/> </ElementType> </Schema> </ElementType> </Schema>
2/23/05 21CS-561 - Advanced Databases
XML Bulk LoadXML Bulk Load Updategrams and OpenXML, are not suitable for Updategrams and OpenXML, are not suitable for
loading large amounts of dataloading large amounts of data
SQLXML provides a facility called the XML Bulk SQLXML provides a facility called the XML Bulk LoadLoad COM objectCOM object
The first step in using the XML Bulk Load is to The first step in using the XML Bulk Load is to define a mapping schema that maps the XML define a mapping schema that maps the XML data to tables and columns in databasedata to tables and columns in database
When the component loads the XML data, it will When the component loads the XML data, it will read it as a stream and use the mapping schema read it as a stream and use the mapping schema to decide where the data goes in the databaseto decide where the data goes in the database
2/23/05 22CS-561 - Advanced Databases
XML Bulk Load (cont.)XML Bulk Load (cont.)
VB Example:VB Example:Set Set objBulkLoad=CreateObject("SQLXMLBulkLoad.SobjBulkLoad=CreateObject("SQLXMLBulkLoad.SQLXMLBulkLoad")QLXMLBulkLoad")
objBulkLoad.ConnectionString = objBulkLoad.ConnectionString = "provider=SQLOLEDB;data "provider=SQLOLEDB;data source=SuperServer;database=Northwind;" source=SuperServer;database=Northwind;"
objBulkLoad.Execute "d:\xml\objBulkLoad.Execute "d:\xml\OrdersSchema.xdr", "d:\xml\OrdersData.xml" OrdersSchema.xdr", "d:\xml\OrdersData.xml"
Set objBulkLoad = NothingSet objBulkLoad = Nothing
2/23/05 23CS-561 - Advanced Databases
Accessing SQL Server Over Accessing SQL Server Over HTTPHTTP
SQL Server's ability to publish data SQL Server's ability to publish data over HTTP is made possible through over HTTP is made possible through SQLISAPI with IISSQLISAPI with IIS An Internet Server API (ISAPI) extensionAn Internet Server API (ISAPI) extension SQLISAPI uses SQLOLEDB, SQL Server's SQLISAPI uses SQLOLEDB, SQL Server's
native OLE DB provider, to access the native OLE DB provider, to access the database associated with a virtual database associated with a virtual directorydirectory
Configuring a virtual directory allows Configuring a virtual directory allows SQL Server's XML features via HTTPSQL Server's XML features via HTTP
2/23/05 24CS-561 - Advanced Databases
Accessing SQL Server over Accessing SQL Server over HTTP (cont.) HTTP (cont.)
Private IntranetPrivate Intranet Send a SELECT … FOR XML query Send a SELECT … FOR XML query
string in URL string in URL Post an XML query template to Post an XML query template to
SQLISAPISQLISAPI Public InternetPublic Internet
Specify a server-side XML schemaSpecify a server-side XML schema Specify a server-side XML query Specify a server-side XML query
templatetemplate
2/23/05 25CS-561 - Advanced Databases
URL QueriesURL Queries
URL queries allow users to specify a URL queries allow users to specify a complete Transact-SQL query via a complete Transact-SQL query via a URLURL
http://localhost/Northwind?http://localhost/Northwind?sql=SELECT+*+FROM+Customers+WHERE+Custsql=SELECT+*+FROM+Customers+WHERE+CustomerId='ALFKI'+OR+CustomerId='ANATR'+FomerId='ALFKI'+OR+CustomerId='ANATR'+FOR+XML+AUTO &root=CustomerListOR+XML+AUTO &root=CustomerList
The first parameter we pass here is The first parameter we pass here is sqlsql The second parameter specifies the The second parameter specifies the
name of the root element for the XML name of the root element for the XML document that will be returned document that will be returned
2/23/05 26CS-561 - Advanced Databases
URL Queries (cont.)URL Queries (cont.)
URL query can also include the URL query can also include the xslxsl parameter parameter Translates the XML document that's Translates the XML document that's
returned by the query into a different formatreturned by the query into a different format
http://localhost/Northwind?sql=SELECT+CustomerId,http://localhost/Northwind?sql=SELECT+CustomerId,+CompanyName+FROM+Customers+FOR+XML+AUTO&root=Custome+CompanyName+FROM+Customers+FOR+XML+AUTO&root=CustomerList&rList&xsl=CustomerList.xslxsl=CustomerList.xsl
http://localhost/Northwind?sql=SELECT+CustomerId,http://localhost/Northwind?sql=SELECT+CustomerId,+CompanyName+FROM+Customers+FOR+XML+AUTO&root=CustomerList&+CompanyName+FROM+Customers+FOR+XML+AUTO&root=CustomerList&xsl=CustomerList.xsl&contenttype=text/xmlxsl=CustomerList.xsl&contenttype=text/xml
2/23/05 27CS-561 - Advanced Databases
Executing Stored Executing Stored Procedures via URLProcedures via URL
Stored Procedure:Stored Procedure:
CREATE PROC ListCustomersXML @CustomerId CREATE PROC ListCustomersXML @CustomerId varchar(10)='%', @CompanyName varchar(80)='%' ASvarchar(10)='%', @CompanyName varchar(80)='%' AS
SELECT CustomerId, CompanyName FROM Customers WHERE SELECT CustomerId, CompanyName FROM Customers WHERE CustomerId LIKE @CustomerId AND CompanyName LIKE CustomerId LIKE @CustomerId AND CompanyName LIKE @CompanyName FOR XML AUTO @CompanyName FOR XML AUTO
URL for executing stored procedure:URL for executing stored procedure:
http://localhost/Northwind?sql=EXEC+ListCustomersXML http://localhost/Northwind?sql=EXEC+ListCustomersXML +@CustomerId='A%25',@CompanyName='An+@CustomerId='A%25',@CompanyName='An%25'&root=CustomerList %25'&root=CustomerList
2/23/05 28CS-561 - Advanced Databases
Template Queries Template Queries Templates are XML documents based on Templates are XML documents based on
the XML-SQL namespace the XML-SQL namespace Mechanism for translating a URL into a query Mechanism for translating a URL into a query
that SQL Server can processthat SQL Server can process
Safer and more widely used technique for Safer and more widely used technique for retrieving data over HTTPretrieving data over HTTP
End users never see the source codeEnd users never see the source code Templates are stored on the Web serverTemplates are stored on the Web server Referenced via a virtual nameReferenced via a virtual name
2/23/05 29CS-561 - Advanced Databases
Sample TemplateSample Template<?xml version='1.0' ?> <?xml version='1.0' ?> <CustomerList xmlns:sql='urn:schemas-microsoft-com:xml-sql'><CustomerList xmlns:sql='urn:schemas-microsoft-com:xml-sql'> <sql:query> <sql:query> SELECT CustomerId, CompanyName FROM Customers FOR XML AUTO SELECT CustomerId, CompanyName FROM Customers FOR XML AUTO </sql:query> </sql:query> </CustomerList> </CustomerList>
Example invocation:Example invocation:
http://localhost/Northwind/http://localhost/Northwind/templates/CustomerList.XMLtemplates/CustomerList.XML
Specify a style sheet to apply to a template Specify a style sheet to apply to a template query:query:
http://localhost/Northwind/Templates/CustomerList3.XML?http://localhost/Northwind/Templates/CustomerList3.XML?xsl=Templates/CustomerList3.xsl&contenttype=text/htmlxsl=Templates/CustomerList3.xsl&contenttype=text/html
2/23/05 30CS-561 - Advanced Databases
TemplatesTemplates Parameterized Templates Parameterized Templates
Permit the user to supply parameters to the query Permit the user to supply parameters to the query <?xml version='1.0' ?> <?xml version='1.0' ?> <CustomerList xmlns:sql='urn:schemas-microsoft-com:xml-<CustomerList xmlns:sql='urn:schemas-microsoft-com:xml-
sql'> sql'> <sql:header> <sql:header> <sql:param <sql:param
name='CustomerId'>%</sql:param>name='CustomerId'>%</sql:param></sql:header> </sql:header> <sql:query> SELECT CustomerId, CompanyName FROM <sql:query> SELECT CustomerId, CompanyName FROM
Customers WHERE CustomerId LIKE Customers WHERE CustomerId LIKE @CustomerId@CustomerId FOR XML FOR XML AUTO </sql:query>AUTO </sql:query>
</CustomerList></CustomerList>
Example invocation:Example invocation:http://localhost/Northwind/Templates/http://localhost/Northwind/Templates/CustomerList2.XML? CustomerId=A%25CustomerList2.XML? CustomerId=A%25
2/23/05 31CS-561 - Advanced Databases
ConclusionsConclusions
SQL Server 2000 has a lot of ways to work SQL Server 2000 has a lot of ways to work with XML, suitable for a number of situationswith XML, suitable for a number of situations
Questions?Questions?
References:References: Conrad, Andrew. Conrad, Andrew. A Survey of Microsoft SQL Server 2000 XML FeaturesA Survey of Microsoft SQL Server 2000 XML Features: :
Microsoft Corporation, 2001Microsoft Corporation, 2001 http://msdn.microsoft.com/xml/default.aspx?pull=/library/en-us/dnexxml/html/http://msdn.microsoft.com/xml/default.aspx?pull=/library/en-us/dnexxml/html/
xml07162001.aspxml07162001.asp Henderson, Ken. Henderson, Ken. Guru's Guide to SQL Server Architecture and Internals, The Guru's Guide to SQL Server Architecture and Internals, The
(Chapter: Using SQL Server's XML Support)(Chapter: Using SQL Server's XML Support) Rys, Michael. Rys, Michael. Bringing the Internet to Your Database: Using SQL Server 2000 Bringing the Internet to Your Database: Using SQL Server 2000
and XML to Build Loosely-Coupled Systemsand XML to Build Loosely-Coupled Systems: Microsoft Corporation: Microsoft Corporation