2091 Building XML-Enabled Applications Using Microsoft SQL S
2091 Building XML-Enabled Applications Using Microsoft SQL S
Released: 04/2001
Delivery Guide
Building XML-Enabled
Applications using Microsoft
SQL Server
2000
Part Number: X08-20854
Information in this document is subject to change without notice. The names of companies,
products, people, characters, and/or data mentioned herein are fictitious and are in no way intended
to represent any real individual, company, product, or event, unless otherwise noted. Complying
with all applicable copyright laws is the responsibility of the user. No part of this document may
be reproduced or transmitted in any form or by any means, electronic or mechanical, for any
purpose, without the express written permission of Microsoft Corporation. If, however, your only
means of access is electronic, permission to print one copy is hereby granted.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
2001 Microsoft Corporation. All rights reserved.
Microsoft, ActiveX, BackOffice, MSDN, MS-DOS, SQL Server, Visual Basic, Visual InterDev,
Visual Studio, Windows, Windows Media, Windows NT, and Windows 2000 are either registered
trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries.
Other product and company names mentioned herein may be the trademarks of their respective
owners.
Course Number: 2091A
Part Number: X08-20854
Released: 04/2001
Building XML-Enabled Applications using Microsoft SQL Server 2000 iii
Contents
Introduction
Course Materials ......................................................................................................2
Prerequisites.............................................................................................................3
Course Outline .........................................................................................................4
Setup ........................................................................................................................5
Microsoft Certified Professional Program...............................................................6
Facilities...................................................................................................................8
Module 1: Using XML and Microsoft SQL Server 2000
Overview..................................................................................................................1
Building Solutions with XML and SQL Server 2000..............................................2
XML Technology Review.....................................................................................11
XML Support in SQL Server 2000........................................................................21
Lab 1: Working with XML....................................................................................28
Multimedia: Microsoft BizTalk Server 2000 and XML (Optional).......................33
Review...................................................................................................................34
Module 2: Retrieving XML Data
Overview..................................................................................................................1
Using the FOR XML Clause to Retrieve Data.........................................................2
Controlling XML Output .......................................................................................13
Lab 2.1: Retrieving XML Data..............................................................................26
Generating Custom XML Formats ........................................................................32
Lab 2.2: EXPLICIT Queries ..................................................................................42
Best Practices.........................................................................................................49
Review...................................................................................................................50
Module 3: Manipulating XML with Transact-SQL
Overview..................................................................................................................1
Creating a Rowset from an XML Document ...........................................................2
Specifying the Structure of a Rowset.....................................................................13
Lab 3: Using OPENXML ......................................................................................26
Best Practices.........................................................................................................33
Review...................................................................................................................34
Module 4: Using ADO to Access XML Data
Overview..................................................................................................................1
Retrieving XML Data with ADO.............................................................................2
Lab 4.1: Creating an ADO Client Application.......................................................16
Using ADO and XML on an ASP-Based Web Site...............................................22
Lab 4.2: Using ADO on a Web Site.......................................................................27
Best Practices.........................................................................................................31
Review...................................................................................................................32
iv Building XML-Enabled Applications using Microsoft SQL Server 2000
Module 5: Using HTTP to Access XML Data
Overview................................................................................................................. 1
Enabling HTTP Access to SQL Databases ............................................................. 2
Publishing XML Templates on the Server............................................................ 14
Lab 5.1: Publishing a SQL Server Database......................................................... 23
Posting Query Templates from the Client............................................................. 30
Publishing a Database Object ............................................................................... 37
Lab 5.2: Accessing a Database Object.................................................................. 42
Best Practices........................................................................................................ 45
Review.................................................................................................................. 47
Module 6: Using Mapping Schemas
Overview................................................................................................................. 1
Using Mapping Schemas ........................................................................................ 2
Using Schemas to Retrieve Data........................................................................... 11
Lab 6.1: Using Mapping Schemas ........................................................................ 21
Mapping Multiple Tables...................................................................................... 30
Lab 6.2: Mapping Multiple Tables........................................................................ 37
Annotating an Existing Schema............................................................................ 42
Lab 6.3: Annotating an Existing Schema.............................................................. 52
Best Practices........................................................................................................ 56
Review.................................................................................................................. 57
Module 7: XML for SQL Tools
Overview................................................................................................................. 1
Modifying Data with Updategrams......................................................................... 2
Lab 7.1: Using Updategrams ................................................................................ 17
Inserting XML Data with the Bulk Load Facility................................................. 22
Lab 7.2: Bulk Loading XML Data........................................................................ 31
Best Practices........................................................................................................ 34
Review.................................................................................................................. 36
Building XML-Enabled Applications using Microsoft SQL Server 2000 v
About This Course
This section provides you with a brief description of the course, audience,
suggested prerequisites, and course objectives.
Description
This course provides students with the knowledge and skills they need to build
applications that exchange data with Microsoft SQL Server
in Extensible
Markup Language (XML) format. The course covers the XML-based features
of Microsoft SQL Server 2000, including XML-based enhancements to the
T-SQL language; generating results in XML format; using query templates;
configuring SQL Server for Internet/intranet access; publishing SQL Server
data on the Internet by using the HTTP protocol; XML data access by using
Microsoft ActiveX Data Objects (ADO) 2.6 and the SQL Server OLE DB
(SQLOLEBD) Provider; writing XML Path Language (XPath) queries; using
XML Data-Reduced (XDR) Schemas; and updating a database with XML data.
Audience
The target audience for this course includes:
Developers of database client applications, including Internet and n-tiered
application clients.
SQL Server database developers who need to query, insert, update, or delete
data from a database by using XML.
SQL Server database administrators who need to publish SQL data as XML.
Student Prerequisites
This course requires that students meet the following prerequisites:
The ability to write basic Transact-SQL statements that query, insert,
update, and delete information from a database. You should be able to use
JOIN statements to retrieve information from multiple tables.
Successful completion of Course 2073A, Programming a Microsoft SQL
Server Database, or equivalent experience designing relational databases,
including the use of primary and foreign keys. You need to know how to
create databases, tables, and stored procedures. Students should also be
familiar with the SQL Server Query Analyzer and SQL Profiler tools.
Successful completion of Course 1905A, Building XML-Based Web
Applications, or equivalent experience using XML, the Extensible
Stylesheet Language (XSL), and Extensible Stylesheet Language
Transformations (XSLT). This includes knowledge of attributes and
elements, schemas, and XPath.
Experience using ADO to access a data source.
The ability to write Microsoft Visual Basic Scripting Edition (VBScript)
code.
The ability to read standard Hypertext Markup Language (HTML) and build
a form to gather and present data.
The ability to create Active Server Pages (ASP) that use the POST and
GET methods, the Response object, and the Session object.
vi Building XML-Enabled Applications using Microsoft SQL Server 2000
Course Objectives
The modules in this course provide instruction and learning activities that allow
students to achieve the following objectives.
In module Students learn to:
1 Describe the XML features provided by SQL Server 2000 and the
SQL Server-XML architecture.
2 Generate and specify the structure of an XML document from SQL
Server data by using Transact-SQL.
3 Insert XML data into SQL Server, and use XML to modify existing
data.
4 Use ADO to access SQL Server data and generate XML.
5 Publish a SQL Server database on the Internet/intranet over HTTP,
and query the data by using a URL.
5 Create and use XML templates to query the database.
6 Create and use annotated schemas to query and transform SQL
Server data.
7 How to use updategrams and the Bulk Load facility..
Building XML-Enabled Applications using Microsoft SQL Server 2000 vii
Course Timing
The following schedule is an estimate of the course timing. Your timing may
vary.
Day 1
Start End Module
9:00 9:30 Introduction
9:30 10:30 Module 1: Using XML and Microsoft SQL Server 2000
10:30 10:45 Break
10:45 11:15 Lab 1: Working with XML
11:15 12:00 Module 2: Retrieving XML Data
12:00 1:00 Lunch
1:00 1:30 Lab 2.1: Retrieving XML Data
1:30 2:45 Module 2: Retrieving XML Data (continued)
2:45 3:00 Break
3:00 3:30 Lab 2.2: EXPLICIT Queries
3:30 4:30 Module 3: Manipulating XML with Transact-SQL
Day 2
Start End Module
9:00 9:30 Day 1 review
9:30 10:30 Module 3: Manipulating XML with Transact-SQL (continued)
10:30 10:45 Break
10:45 11:15 Lab 3: Using OPENXML
11:15 12:00 Module 4: Using ADO to Access XML Data
12:00 1:00 Lunch
1:00 1:15 Lab 4.1: Creating an ADO Client Application
1:15 1:30 Module 4: Using ADO to Access XML Data (continued)
1:30 2:00 Lab 4.2: Using ADO on a Web Site
2:00 2:30 Module 5: Using HTTP to Access XML Data
2:30 2:45 Break
2:45 3:30 Lab 5.1: Publishing a SQL Server Database
3:30 4:00 Module 5: Using HTTP to Access XML Data (continued)
viii Building XML-Enabled Applications using Microsoft SQL Server 2000
Day 3
Start End Module
9:00 9:30 Day 2 review
9:30 10:00 Module 5: Using HTTP To Access XML Data (continued)
10:00 10:15 Lab 5.2: Accessing a Database Object
10:15 10:30 Module 5: Best Practices and Review
10:30 10:45 Break
10:45 11:15 Module 6: Using Mapping Schemas
11:15 11:45 Lab 6.1: Using Mapping Schemas
11:45 12:45 Lunch
12:45 1:15 Module 6: Using Mapping Schemas (continued)
1:15 1:45 Lab 6.2: Mapping Multiple Tables
1:45 2:15 Module 6: Using Mapping Schemas (continued)
2:15 2:30 Break
2:30 3:00 Lab 6.3: Annotating an Existing Schema
3:00 3:45 Module 7: XML for SQL Tools
3:45 4:15 Lab 7.1: Using Updategrams
4:45 5:00 Lab 7.2: Bulk Loading XML Data
Building XML-Enabled Applications using Microsoft SQL Server 2000 ix
Trainer Materials Compact Disc Contents
The Trainer Materials compact disc contains the following files and folders:
Autorun.exe. When the CD is inserted into the CD-ROM drive, or when
you double-click the autorun.exe file, this file opens the CD and allows you
to browse the Student Materials or Trainer Materials compact discs, or
install Microsoft Internet Explorer.
Default.htm. This file opens the Trainer Materials Web page.
Readme.txt. This file contains a description of the compact disc contents
and setup instructions in ASCII format (nonMicrosoft Word document).
2091A_ms.doc. This file is the Manual Classroom Setup Guide. It contains
the steps for manually installing the classroom computers.
2091A_sg.doc. This file is the Classroom Setup Guide. It contains a
description of classroom requirements, classroom configuration, instructions
for using the automated classroom setup scripts, and the Classroom Setup
Checklist.
StudentCD. This folder contains the Web page that provides students with
links to course-related resources, including additional reading, review and
lab answers, lab files, multimedia presentations, and course-related Web
sites.
Errorlog. This folder contains a template that is used to record any errors
and corrections that you find in the course.
Fonts. This folder contains fonts that are required in order to view the
Microsoft PowerPoint presentation and Web-based materials.
Mplayer. This folder contains files that are required to install Microsoft
Windows Media
Player.
Powerpnt. This folder contains the PowerPoint slides that are used in this
course.
Pptview. This folder contains the PowerPoint Viewer, which is used to
display the PowerPoint slides.
Setup. This folder contains the files that install the course and related
software to computers in a classroom setting.
Tools. This folder contains files and utilities used to complete the setup of
the instructor computer.
Webfiles. This folder contains the files that are required in order to view the
course Web page. To open the Web page, open Windows Explorer, and in
the root directory of the compact disc, double-click Default.htm or
Autorun.exe.
x Building XML-Enabled Applications using Microsoft SQL Server 2000
Student Materials Compact Disc Contents
The Student Materials compact disc contains the following files and folders:
Autorun.exe. When the CD is inserted into the CD-ROM drive, or when
you double-click the autorun.exe file, this file opens the CD and allows you
to browse the Student Materials CD or install Internet Explorer.
Default.htm. This file opens the Student Materials Web page. It provides
you with course-related resources, including additional reading, review and
lab answers, lab files, multimedia presentations, and course-related Web
sites.
Readme.txt. This file contains a description of the compact disc contents
and setup instructions in ASCII format (nonMicrosoft Word document).
2091A_ms.doc. This file is the Classroom Setup Guide. It contains a
description of classroom requirements, classroom setup instructions, and the
classroom configuration.
AddRead. This folder contains additional reading related to this course. If
there are no additional reading files, this folder does not appear.
Appendix. This folder contains appendix files for this course. If there are no
appendix files, this folder does not appear.
Democode. This folder contains demonstration code. If there is no
demonstration code, the Democode folder does not appear.
Fonts. This folder contains fonts that are required in order to view the
PowerPoint presentation and Web-based materials.
Ie5. This folder contains Internet Explorer 5.5.
Labs. This folder contains files that are used in the hands-on labs. These
files may be used to prepare the student computers for the hands-on labs.
Media. This folder contains files that are used in multimedia presentations
for this course. If this course does not include any multimedia presentations,
this folder does not appear.
Menu. This folder contains elements for autorun.exe.
Mplayer. This folder contains files that are required to install Windows
Media Player.
Practices. This folder contains files that are used in the hands-on practices.
If there are no practices, the Practices folder does not appear.
Sampapps. This folder contains the sample applications associated with this
course. If there are no associated sample applications, the Sampapps folder
does not appear.
Sampcode. This folder contains sample code that is accessible through the
Web pages on the Student Materials compact disc. If there is no sample
code, the Sampcode folder does not appear.
Sampsite. This folder contains files that create the sample site associated
with this course. If there is no sample site, the Sampsite folder does not
appear.
Building XML-Enabled Applications using Microsoft SQL Server 2000 xi
Setup. This folder contains additional files that may be required for lab
setup. If no additional files are required, the Setup folder does not appear.
Webfiles. This folder contains the files that are required in order to view the
course Web page. To open the Web page, open Windows Explorer, and in
the root directory of the compact disc, double-click Default.htm or
Autorun.exe.
Wordview. This folder contains the Word Viewer that is used to view any
Word document (.doc) files that are included on the compact disc. If no
Word documents are included, this folder does not appear.
xii Building XML-Enabled Applications using Microsoft SQL Server 2000
Document Conventions
The following conventions are used in course materials to distinguish elements
of the text.
Convention Use
Indicates an introductory page. This symbol appears next
to a topic heading when additional information on the
topic is covered on the page or pages that follow it.
bold Represents commands, command options, and syntax that
must be typed exactly as shown. It also indicates
commands on menus and buttons, dialog box titles and
options, and icon and menu names.
italic In syntax statements or descriptive text, indicates
argument names or placeholders for variable information.
Italic is also used for introducing new terms, for book
titles, and for emphasis in the text.
Title Capitals Indicate domain names, user names, computer names,
directory names, and folder and file names, except when
specifically referring to case-sensitive names. Unless
otherwise indicated, you can use lowercase letters when
you type a directory name or file name in a dialog box or
at a command prompt.
ALL CAPITALS Indicate the names of keys, key sequences, and key
combinationsfor example, ALT+SPACEBAR.
monospace Represents code samples or examples of screen text.
[ ] In syntax statements, enclose optional items. For example,
[filename] in command syntax indicates that you can
choose to type a file name with the command. Type only
the information within the brackets, not the brackets
themselves.
{ } In syntax statements, enclose required items. Type only
the information within the braces, not the braces
themselves.
| In syntax statements, separates an either/or choice.
Indicates a procedure with sequential steps.
... In syntax statements, specifies that the preceding item may
be repeated.
.
.
.
Represents an omitted portion of a code sample.
Contents
Introduction 1
Course Materials 2
Prerequisites 3
Course Outline 4
Setup 5
Microsoft Certified Professional Program 6
Facilities 8
Introduction
Information in this document is subject to change without notice. The names of companies,
products, people, characters, and/or data mentioned herein are fictitious and are in no way intended
to represent any real individual, company, product, or event, unless otherwise noted. Complying
with all applicable copyright laws is the responsibility of the user. No part of this document may
be reproduced or transmitted in any form or by any means, electronic or mechanical, for any
purpose, without the express written permission of Microsoft Corporation. If, however, your only
means of access is electronic, permission to print one copy is hereby granted.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
2001 Microsoft Corporation. All rights reserved.
Microsoft, ActiveX, BackOffice, BizTalk, MSDN, MS-DOS, SQL Server, Visual Basic, Visual
C++, Visual InterDev, Visual J++, Visual Studio, Windows, Windows Media, Windows NT, and
Windows 2000 are either registered trademarks or trademarks of Microsoft Corporation in the
U.S.A. and/or other countries.
Other product and company names mentioned herein may be the trademarks of their respective
owners.
Introduction iii
Instructor Notes
This module provides students with an overview of the course content,
materials, and logistics.
Course Materials and Preparation
Required Materials
To teach this course, you need the following materials:
Delivery Guide
Trainer Materials compact disc
Preparation Tasks
To prepare for this course, you must complete the Course Preparation Checklist
that is included with the trainer course materials.
Presentation:
30 Minutes
iv Introduction
Module Strategy
Use the following strategies to present this module:
Course 2091A: Building XML-Enabled Applications Using Microsoft
SQL Server
2000
Show the slide that displays the course number and course title.
Introduction
Welcome students to the course and introduce yourself. Provide a brief
overview of your background to establish credibility.
Have students introduce themselves and provide their background, product
experience, and expectations of the course.
Record student expectations on a whiteboard or flip chart that you can
reference later in class.
Course Materials
Explain the purpose of all materials used in this course.
Tell students that they will have an opportunity at the end of the class to
provide feedback on the course and facilities by using the Microsoft Online
Evaluation System.
Prerequisites
Provide the students with the list of prerequisites that they should have met
before taking this course. This is an opportunity for you to identify students
who may not have the appropriate background or experience to attend this
course.
Course Outline
Provide an overview of each module and what students will learn.
Explain how this course will meet students expectations by relating the
information covered in individual modules to their expectations.
Setup
Provide the students with any necessary setup information for the course.
Microsoft Certified Professional Program
Inform students about the Microsoft Certified Professional (MCP) program
and the various certification options.
Facilities
Explain the facility information for the training site.
Introduction 1
Introduction
Name
Company affiliation
Title / function
Job responsibility
SQL Server experience
XML development experience
Expectations for the course
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Topic Objective
To introduce yourself,
establish credibility, meet
students, and set student
expectations for the course.
Lead-in
Good morning. Welcome to
Course 2091A, Building
XML-Enabled Applications
Using Microsoft SQL
Server
2000.
My name is...
Introduce yourself.
Provide a brief overview of
your background to
establish credibility as an
instructor in this set of
technologies.
Ask students to introduce
themselves, addressing the
bulleted items on the slide.
Delivery Tip
As students introduce
themselves, use a
whiteboard or flip chart to
record their expectations of
the course.
2 Introduction
Course Materials
Name card
Student workbook
Student Materials compact disc
Course evaluation
*****************************ILLEGAL FOR NON-TRAINER USE******************************
The following materials are included with your kit:
Name card. Write your name on both sides of the name card.
Student workbook. The student workbook contains the material covered in
class, in addition to the hands-on lab exercises.
Student Materials compact disc. The Student Materials compact disc
contains the Web page that provides you with links to course-related
resources, including additional readings, review and lab answers, lab files,
multimedia presentations, and course-related Web sites.
To open the Web page, insert the Student Materials compact disc into
the CD-ROM drive, and then double-click Autorun.exe or Default.htm in
the root directory of the compact disc.
Course evaluation. At the conclusion of this course, please complete the
course evaluation to provide feedback on the instructor, course, and
software product. Your comments will help us to improve future courses.
To provide additional comments or inquire about the Microsoft Certified
Professional program, send e-mail to mcp@msprograms.com
Topic Objective
To identify and describe the
course materials.
Lead-in
We have provided
everything you need for this
course. You will find the
following materials at your
desk...
Describe the contents of the
student workbook and the
Student Materials compact
disc.
Have students write their
names on both sides of the
name card.
Tell students that a course
evaluation must be
completed at the end of the
course.
Tell students where they
can send comments.
Delivery Tip
Demonstrate how to open
the Web page provided on
the Student Materials
compact disc. On the
Trainer Materials compact
disc, double-click
Autorun.exe or
Default.htm in the
StudentCD folder.
Note
Introduction 3
Prerequisites
Intermediate experience programming in Transact-SQL
Course 2073A, Programming a Microsoft SQL Server
Database
Intermediate experience using XML
Course 1905A, Building XML-Based Web Applications
Scripting and ADO: VBScript that accesses a data
source
Ability to build a form in HTML
ASP pages that use:
POST and GET methods
Response and Session objects
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Student Prerequisites
To get the most from this course, you should come prepared with the following
prerequisites:
The ability to write basic Transact-SQL statements that query, insert,
update, and delete information from a database. You should be able to use
JOIN statements to retrieve information from multiple tables.
Successful completion of Course 2073A, Programming a Microsoft
SQL Server Database, or equivalent experience designing relational
databases, including the use of primary and foreign keys. You need to know
how to create databases, tables, and stored procedures. Students should also
be familiar with the SQL Server Query Analyzer and SQL Profiler tools.
Successful completion of Course 1905A, Building XML-Based Web
Applications, or equivalent experience using the Extensible Markup
Language (XML), the Extensible Stylesheet Language (XSL), and
Extensible Stylesheet Language Transformations (XSLT). This includes
knowledge of attributes and elements, schemas, and the XML Path
Language (XPath).
Experience using Microsoft ActiveX Data Objects (ADO) to access a data
source.
The ability to write Microsoft Visual Basic, Scripting Edition (VBScript)
code.
The ability to read standard Hypertext Markup Language (HTML) and build
a form to gather and present data.
The ability to create Active Server Pages (ASP) that use the POST and
GET methods, the Response object, and the Session object.
Topic Objective
To present and describe the
prerequisites for this course.
Lead-in
The following prerequisite
knowledge is needed for this
course.
4 Introduction
Course Outline
Module 1: Using XML and Microsoft SQL Server 2000
Module 2: Retrieving XML Data
Module 3: Manipulating XML with Transact-SQL
Module 4: Using ADO to Access XML Data
Module 5: Using HTTP To Access XML Data
Module 6: Using Mapping Schemas
Module 7: XML for SQL Tools
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Module 1, Using XML and Microsoft SQL Server
2000.
After completing this module, students will be able to:
Use XML to represent business data.
Format an XML document by referencing an Extensible Stylesheet
Language (XSL) style sheet.
Use XML Path Language (XPath) expressions in XSL programming.
List the XML features in SQL Server 2000.
Describe the SQL Server 2000 XML architecture.
Materials and Preparation
This section provides the materials and preparation tasks that you need to teach
this module.
Required Materials
To teach this module, you need the following materials:
Microsoft PowerPoint file 2091A_01.ppt
The demo code provided for this chapter on the Instructor Materials
compact disc
Preparation Tasks
To prepare for this module, you should:
Read all of the materials for this module.
Complete the lab.
Practice the demonstration.
Presentation:
60 Minutes
Lab:
30 Minutes
iv Module 1: Using XML and Microsoft SQL Server 2000
Instructor Setup for a Lab
This section provides setup instructions that are required in order to prepare the
instructor computer or classroom configuration for a lab.
Lab 1: Working with XML
To prepare for the lab
Verify that the lab files have been installed on each student computer.
Demonstrations
This section provides demonstration procedures that will not fit in the margin
notes or are not appropriate for the student notes.
A SQL Server XML-Based Solution
To prepare for the demonstration
1. Install the sample application by executing SETUP.bat in the folder
<install folder>\SampApps\SQLXMLAPP.
2. Examine the Active Server Pages (ASP) code in the folder
<system drive>\InetPub\WWWRoot\Retailer.
3. Examine the templates and schemas in the folders SupplierIntranet,
SupplierExtranet, and ShippingCo.
4. Use the SQL Server Query Analyzer to examine the Retailer, Supplier, and
ShippingCo databases. In particular, examine the definitions for the tables
and stored procedures.
To demonstrate the Retailer site
1. On the desktop, click the Retailer Web Site shortcut to move to the
Retailer Web site. Explain that this site consists of ASP pages that retrieve
data from SQL Server as XML. Style sheets are then applied to the XML to
produce the HTML pages. The advantage of this approach is that by
applying different style sheets, the presentation logic can be changed. The
content remains the same.
2. Click the Login link, and then click Register to create a user account (or log
in as Graeme with a password of password).
3. View the various product categories, pointing out that there is only one
product in the category Cables etc.
4. Add any two items to the basket and then view the basket.
5. Check out by providing a fictitious address and credit-card number, and
note the order number. Explain that the order has been sent to the supplier as
an XML document.
Module 1: Using XML and Microsoft SQL Server 2000 v
To demonstrate the supplier intranet application
1. On the desktop, click the Supplier Intranet Site shortcut to move to the
Supplier Web site. Explain that this is a SQL Server Internet Server
Application Programming Interface (SQLISAPI) application, hosted by
Internet Information Services (IIS), which allows XML data to be retrieved
from the Supplier database. In this scenario, the application is an Order
Picking application used by warehouse employees to prepare goods for
delivery.
2. Right-click in the middle frame where the orders are listed, and choose
View Source. Point out that this application sends XML to the browser,
relying on client-side support for XML. Close Notepad.
3. Click the order that you placed earlier. The details of this order have been
inserted into the Supplier database from the XML document sent by the
Retailer application. These details were inserted by using SQL Servers
OpenXML function.
4. Pick all of the items, and then click Ready for Dispatch.
5. Explain that clicking Send Delivery Request sends an XML Updategram
document to the shipping company over the Hypertext Transfer Protocol
(HTTP), and inserts a delivery request into the ShippingCo database. Click
Send Delivery Request.
6. Click the link to the Shipping Company Web site and confirm that the
delivery details have been sent. Explain that this is another SQLISAPI
application, but that this time the style sheet is applied on the server, and
therefore any browser can access it.
To demonstrate the Catalog Import tool
1. On the desktop, click the Catalog Import Tool shortcut to view the
contents of the CatalogImport folder. Explain that this is a VBScript
application used by the retailer to perform the following tasks:
a. Download catalog data over HTTP from an annotated schema published
in a SQLISAPI application at the supplier.
b. Write the catalog data to an XML file for logging purposes.
c. Import the XML catalog data into the retailer database by using the SQL
XML Bulk Load facility.
2. Double-click the script to execute it. When the script completes, view the
catalog.xml file that was produced.
3. Open the Retailer Web site and view the various product categories. Note
that more products have been imported into the database.
Using an XML Schema
To prepare for the demonstration
1. Ensure that the XML Validation Tools for Internet Explorer have been
installed correctly by opening the file Order.xml in the folder
<install folder>\DemoCode\Mod01\Schema. Right-click anywhere in the
document to verify that the option to Validate XML is present
2. Practice the steps in the margin notes.
vi Module 1: Using XML and Microsoft SQL Server 2000
Using XPath Expressions
To prepare for the demonstration
1. Practice the steps shown in the margin notes.
2. Examine the document Order.xml and the script OrderData.vbs.
Applying XSL Style Sheets
To prepare for the demonstration
1. Ensure that the Microsoft XML Parser 3.0 (MSXML3) has been installed
correctly, and that XMLInst.exe has been used to replace older versions of
the DLL.
2. Practice the steps shown in the margin notes.
SQLOLEDB Services
To prepare for the demonstration
1. Practice the steps shown in the margin notes.
2. Examine the code in GetProducts.vbs. In particular, note the use of an
XPath query to specify all Product elements if no category is supplied, or
Product elements containing a CategoryID child element with a specific
value if a CategoryID is supplied. The relevant code is shown in the
following example:
If iCategoryID = "" Then
CmdProducts.CommandText = "Products"
Else
CmdProducts.CommandText = "Products[CategoryID="
& iCategoryID & "]"
End If
3. Examine the Transact-SQL statement recorded by the SQL Server Profiler.
Note that it is a SELECTFOR XML statement that uses the EXPLICIT
modifier. Also note that the CategoryID supplied in the XPath query is used
in the WHERE clause.
4. For large classrooms, you may want to increase the font size in Notepad
(from the Format menu) and in Profiler (on the Display tab of the Options
dialog box, available from the Tools menu).
Module 1: Using XML and Microsoft SQL Server 2000 vii
Module Strategy
Use the following strategies to present this module:
Building Solutions with XML and SQL Server 2000
Begin by discussing the need to integrate applications and businesses, and
the importance of separating data from presentation when dealing with
multiple client types. Stress that these are the types of problems that XML
can be used to address.
Emphasize that relational databases, such as SQL Server, are an efficient
way to store data. Contrast this with XML, which provides an effective way
to exchange data. The main problems for the developer are:
Extracting data from a relational database in XML format.
Inserting data from an XML document into a relational database.
SQL Server 2000 XML-related functionality is designed to help you
perform these tasks.
Use the demonstration to discuss the kinds of solutions that you can build by
using XML and SQL Server. The technologies used in this sample
application will be covered in the remainder of the course.
XML Technology Review
This should be review for most students. If some students have not used
XML extensively, and are unfamiliar with schemas, XPath, or XSL, use the
demonstrations to cover the main points that should be understood when
using the XML functionality in SQL Server.
XML Support in SQL Server 2000
The information in this module is designed to provide a very high-level
overview of the XML-related features in SQL Server 2000. Do not go into
too much detail about the use of Microsoft ActiveX Data Objects (ADO)
and HTTP to retrieve XML data, or about the XML-related Transact-SQL
statement, templates, annotated schemas, Updategrams, or the Bulk Load
facility, as they will be covered in later modules. Instead, emphasize why
these features have been added to the product, and show how SQL Server
XML support can be a very useful tool in many business integration
scenarios.
When discussing the architecture of the XML functionality in SQL Server
2000, emphasize the role of the SQL Server OLE DB Provider
(SQLOLEDB Provider). This is the core component in building SQL Server
XML-based solutions.
Module 1: Using XML and Microsoft SQL Server 2000 1
Overview
Building Solutions with XML and SQL Server 2000
XML Technology Review
XML Support in SQL Server 2000
*****************************ILLEGAL FOR NON-TRAINER USE******************************
In this module, you will learn how to use the Extensible Markup Language
(XML) and Microsoft SQL Server
by
using Microsoft ActiveX Data Objects (ADO).
After completing this module, students will be able to:
Construct an XML query template.
Use a Command object and Stream objects to submit an XML query.
Apply a style sheet to the results of an XML query that uses ADO.
Return an XML query result to the Active Server Pages (ASP) Response
object.
Specify the output encoding of an XML query result.
Materials and Preparation
This section provides the materials and preparation tasks that you need to teach
this module.
Required Materials
To teach this module, you need Microsoft PowerPoint file 2091a_04.ppt.
Preparation Tasks
To prepare for this module, you should:
Read all of the materials for this module.
Complete the labs.
Instructor Setup for a Lab
This section provides setup instructions that are required to prepare the
instructor computer or classroom configuration for a lab.
Lab 4.1: Creating an ADO Client Application
To prepare for the lab
Ensure that the students perform the setup procedure on the introductory
page of the lab.
Presentation:
60 Minutes
Lab:
30 Minutes
iv Module 4: Using ADO to Access XML Data
Module Strategy
Use the following strategies to present this module:
Retrieving XML Data with ADO
Emphasize that the ability to save recordsets as XML is not specific to SQL
Serverthis approach can be used with any OLE DB provider to generate
XML data from any source (for example, Microsoft Access or Microsoft
Active Directory). However, if you want to be able to take advantage of
native support for XML in SQL Server, you must use the SQL Server OLE
DB Provider (SQLOLEDB Provider).
Use the slide Submitting an XML Query with ADO as a high-level
introduction to the process. Then cover each step in detail on the appropriate
slide.
Using ADO and XML on an ASP-Based Web Site
Discourage students from writing ADO code directly in an ASP page.
Emphasize that components are a much more scalable and flexible solution.
When building a Web site with ADO and XML, the most important
property is the XSL property. Emphasize that you can use the XSL property
to transform the retrieved XML into Hypertext Markup Language (HTML),
Wireless Markup Language (WML), or any other presentation format
required.
The use of the SS Stream Flags property is relatively specialized. Explain
that you can use this property as a way to limit access to files in client
applications where the user can specify the location of the style sheet to be
used. Because this is not a common scenario, students will rarely use this
property with ADO.
Emphasize that XML data islands can only be used with XML-aware
browsers such as Microsoft Internet Explorer.
Module 4: Using ADO to Access XML Data 1
Overview
Retrieving XML Data with ADO
Using ADO and XML on an ASP-Based Web Site
*****************************ILLEGAL FOR NON-TRAINER USE******************************
After completing this module, you will be able to:
Construct an Extensible Markup Language (XML) query template.
Use a Command object and Stream objects to submit an XML query.
Apply a style sheet to the results of an XML query that uses Microsoft
ActiveX Data Objects (ADO).
Return an XML query result to the Active Server Page (ASP) Response
object.
Specify the Output Encoding property of an XML query result.
Topic Objective
To provide an overview of
the module topics and
objectives.
Lead-in
In this module, you will learn
how ADO can be used to
retrieve XML data from
Microsoft SQL Server.
2 Module 4: Using ADO to Access XML Data
Retrieving XML Data with ADO
Using ADO to Retrieve XML
ADO Support for XML
Persisting ADO Recordsets as XML
Submitting an XML Query with ADO
Using a Command Object
Building XML Query Templates for ADO Commands
Assigning a Query to a Command Object
Creating a Result Stream
Executing a Query
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Mostdevelopers working with the Microsoft Windows operating system use
ADO as the preferred data access technology for multiple diverse data sources.
If you have already created a recordset, you can use ADO to transform it into
XML. Alternatively, you can use Microsoft SQL Server
2000 database.
After completing this module, you will be able to:
Create an IIS virtual directory that references a SQL Server 2000 database.
Test connectivity to a SQL Server 2000 database via HTTP.
Create an Extensible Markup Language (XML) template to retrieve XML
data over HTTP.
Create a client application that uses the HTTP POST method to publish
templates to SQL Server 2000.
Use HTTP to enable access to database objects.
The terms virtual directory and virtual root both refer to an IIS
virtual directory.
Topic Objective
To provide an overview of
the module topics and
objectives.
Lead-in
In this module, you will learn
how SQL Server enables
you to use the Hypertext
Transfer Protocol to publish
databases.
Note
2 Module 5: Using HTTP to Access XML Data
Enabling HTTP Access to SQL Databases
Publishing SQL Server Data over HTTP
SQL Server 2000 Virtual Directory Architecture
Creating a Virtual Directory for SQL Server
Securing a SQL Server Virtual Directory
Demonstration: Creating a Virtual Directory for SQL
Server
Testing HTTP Connectivity to SQL Server
Encoding URL Characters
*****************************ILLEGAL FOR NON-TRAINER USE******************************
The easiest way to publish SQL Server 2000 databases over HTTP is with
Microsoft Internet Information Services. In this section, you will learn how to
create a secure IIS virtual directory for your SQL Server 2000 data sources.
You will also learn how to use a Uniform Resource Locator (URL) query to test
a virtual directory.
Topic Objective
To introduce the topics in
this section.
Lead-in
In this section, you will see
how to use an IIS virtual
directory publish a
SQL Server database.
Module 5: Using HTTP to Access XML Data 3
Publishing SQL Server Data over HTTP
Retailer Shipping Co.
Supplier
Extranet
Intranet
site
Web
site
Browser
Catalog
Application
Browser
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Publishing SQL Server data by using a virtual directory is useful in the
following data access scenarios:
Intranet applications
In most business organizations, users need to access data in a corporate
database. By publishing a SQL Server database through an IIS virtual
directory, users can access the data by using a browser such as Microsoft
Internet Explorer. This reduces the need to build and deploy a custom data
access client application. For example, a supplier might make customer
order data available to warehouse employees through an intranet site that
publishes data from a SQL Server database.
Extranet applications
In a business-to-business e-commerce scenario, an organization might need
to access data from another organization programmatically over the Internet.
By publishing the data in a virtual directory, the data can be retrieved by a
client application that is capable of making an HTTP request. For example,
a retailer might download catalog information from a supplier through an
HTTP connection over the Internet.
Topic Objective
To describe scenarios
where data can be
published in a virtual
directory and accessed by
using HTTP.
Lead-in
The ability to publish data in
a SQL Server database
through a virtual directory
for access over HTTP can
be useful in a number of
scenarios.
Delivery Tip
This slide builds
automatically to show data
being published on an
intranet site, an extranet
site, and a Web site.
To restart the build, press
the LEFT ARROW key on
the keyboard.
4 Module 5: Using HTTP to Access XML Data
Web sites
Many Web sites are used primarily to publish data. Allowing access to a
SQL Server database through a virtual directory makes it possible to publish
data on a Web site with minimal development effort. For example, a
shipping company could make parcel shipping status information available
to customers over the Internet.
Publishing a database through a virtual directory requires less coding
effort than building a complete Active Server Pages (ASP)based site.
However, if your Web application must include complex business logic, such as
a custom authentication model, it may be more sensible to build an ASP-based
solution that accesses the data by using Microsoft ActiveX Data Objects
(ADO).
Note
Module 5: Using HTTP to Access XML Data 5
SQL Server 2000 Virtual Directory Architecture
Internet Information Services
OLE DB
SQL Server 2000
FOR XML
FOR XML HTTP-aware applications
HTTP-aware applications
Business partners
Business partners
Web browser
Web browser
Clients
Sqlisapi.dll Sqlxmlx.dll
Virtual name
Virtual name
http://webserver/data
An XML
document
An XML
document
Virtual directory
Virtual directory
*****************************ILLEGAL FOR NON-TRAINER USE******************************
SQL Server 2000 databases can be published in an IIS virtual directory.
Publishing Data in a Virtual Directory
Microsoft Windows 2000 and Windows NT 4.0 provide IIS to allow you to
create a Web site that publishes information in a folder, making it accessible
through an HTTP request. The folder containing a Web application is known as
a virtual directory (or sometimes a virtual root).
Virtual directories are accessed over HTTP by specifying a URL of the form
http://servername/virtualdirectoryname. The servername portion of the URL
can be simply the name of a server running IIS (for example, Webserver), or a
fully qualified domain name of an Internet host.
Using the SQLISAPI DLL
Most virtual directories are used to publish HTML pages, or dynamic ASP-
based applications. However, a virtual directory can also be used to publish an
Internet Services Application Programming Interface (ISAPI) application. This
is a dynamic-link library (DLL) that routes any HTTP requests to the
appropriate virtual directory.
SQL Server 2000 provides an ISAPI application (SQLISAPI) that is
implemented in a file called SQLISAPI.dll. This application intercepts requests
for data and retrieves it from a specified SQL Server database by using an OLE
DB connection. Requests for XML data are processed on the SQL Server by the
sqlxmlx.dll component, which retrieves the data and sends the XML results
back to the SQLISAPI application. The XML data is then returned to the client
over HTTP.
Topic Objective
To review the functional
components of a solution
that uses HTTP, SQL, and
IIS.
Lead-in
The main reason to use
HTTP is to integrate clients
whose only common
connection method is HTTP.
IIS works with SQL Server
to accomplish this goal.
6 Module 5: Using HTTP to Access XML Data
Using Virtual Names
Although it is possible to allow access to data through SQL queries submitted
directly to the virtual directory, it is more common to create predefined query
templates or schemas that encapsulate data access logic. These are published in
a virtual name. A virtual name is conceptually a subfolder of the virtual
directory, although it does not necessarily need to represent a physical folder
(and even if it does, the folder can be in a different physical path from the
virtual directory). A virtual name can be one of the following three types:
Template. A folder in which XML template files are published.
Schema. A folder in which mapping schemas are published.
DBObject. A virtual name used to access binary objects in the database.
Using the Configure SQL XML Support in IIS Tool
SQLISAPI-based virtual directories and virtual names are created by using the
Configure SQL XML Support in IIS tool. This tool is implemented as a
Microsoft Management Console (MMC) snap-in and can be used to manage all
aspects of SQLISAPI virtual directory management.
Module 5: Using HTTP to Access XML Data 7
Creating a Virtual Directory for SQL Server
1. Choose a name and a physical path
2. Connect to a SQL Server database
3. Configure security
4. Choose an HTTP request option
5. Create a virtual name for any template file, mapping
schema, or database object
6. Specify any connection string parameters
*****************************ILLEGAL FOR NON-TRAINER USE******************************
To enable IIS to communicate directly with SQL Server, you first need to create
a virtual directory by using the Configure SQL XML Support in IIS tool. This
utility instructs IIS to create an association between the new virtual directory
and a SQL Server database.
Creating a SQL Server Virtual Directory
You need to make the following decisions when creating a virtual directory:
1. Choose a name and a physical path for the virtual directory.
2. Connect the virtual directory to a specific database on a SQL Server.
3. Configure security for the virtual directory.
4. Specify the kinds of requests that will be allowed to this virtual directory.
5. If you want to allow URLs to reference a template file, mapping schema, or
database object, create a virtual name for any of these you plan to use.
6. When necessary, specify any additional connection string parameters and
caching options.
Topic Objective
To explain the decisions you
need to make when you
create a virtual directory for
a SQL Server database.
Lead-in
SQL Server virtual
directories are IIS
applications that use the
ISAPI DLL Extension
provided with SQL Server.
8 Module 5: Using HTTP to Access XML Data
Securing a SQL Server Virtual Directory
Internet Information Services SQL Server 2000 Clients
Trusted server model:
IIS accesses the database on behalf of all users
Impersonation/delegation model:
IIS uses each users credentials to access SQL Server
IIS is authenticated by using:
SQL login& password or
Windows account & password
User is authenticated by using
SQL login& password or
Windows account & password
*****************************ILLEGAL FOR NON-TRAINER USE******************************
There are two general security models for distributed applications such as a
Web application. These are often referred to as the trusted server model and the
impersonation/delegation model. In the trusted server model, the user account
belonging to the IIS server is used to access the database, and the end users are
considered anonymous. In the impersonation/delegation model, IIS passes the
users credentials (in other words, it impersonates the user) when making a
request to SQL Server.
Using the Trusted Server Model
To configure a SQL Server virtual directory to use the trusted server model, on
the Security tab, select Always log on as:, and then provide the username and
password for a SQL Server or Windows login. All data requests, regardless of
the end user, will be made by using the user credentials specified here. You
must ensure that the account you specify has sufficient permissions to access
data from the SQL Server database.
Using the Impersonation/Delegation Model
In the impersonation/delegation model, each user provides separate security
credentials to IIS. IIS then accesses SQL Server by using the security
credentials provided by the user.
You can configure your virtual directory to require Windows Integrated
Authentication, in which case the user must provide Windows network login
credentials, or Basic Authentication (Clear Text) to a SQL Server Account, in
which case the user must provide a SQL Server login name and password.
The term impersonation is used when SQL Server is running on the
same computer as IIS. The term delegation is used when IIS and SQL Server
are running on separate computers. Windows NT 4.0 does not support
delegation of Windows accounts.
Topic Objective
To describe how to secure a
SQL Server virtual directory.
Lead-in
There are two general
security models for
distributed applications: the
trusted server model and
the impersonation/
delegation model.
Note
Module 5: Using HTTP to Access XML Data 9
Choosing an Authentication Method
Whether you choose the trusted server or impersonation/delegation security
model, you still must decide how SQL Server will authenticate user requests.
SQL Server can authenticate users based on a Windows user account, or a
SQL Server login.
Using a Windows Account for SQL Server Authentication
By default, SQL Server 2000 authenticates user requests based on the users
Windows account. If the user (or a group that the user has membership in) has
been granted access to the database, the request succeeds and the data is
returned; otherwise the request fails and an error is returned.
When using the trusted server model in a SQL Server virtual directory, the
Windows account specified in the Security tab of the New Virtual Directory
Properties dialog box is used to access SQL Server. If this user account has
been granted appropriate permissions, the data is returned to IIS and then sent
to the client that made the original request.
When using the impersonation/delegation model, the user must provide a valid
Windows account name and password for access to SQL Server. If the user is
already logged on to a Windows network, his or her credentials are forwarded
with the request; otherwise the user is prompted to enter a Windows username
and password. The user must access the virtual directory by using an
application that supports Windows authentication (such as Internet Explorer),
so that the credentials can be passed securely over the network.
Using a SQL Server Login
You can configure SQL Server to allow users to access the server by using a
SQL Server login account. This is a user account maintained in the SQL Server
master database, and is separate from the Windows security system. Generally,
you should use this configuration only for backward compatibility, as it allows
users to bypass Windows security.
When using a SQL Server login with the trusted server model, the SQL Server
login name and password specified in the Security tab of the New Virtual
Directory Properties dialog box is used to access SQL Server for every user
request.
When using a SQL Server login with the impersonation/delegation model, the
user is prompted to enter a SQL Server username and password. This
information is then sent unencrypted across the network to IIS, and passed to
SQL Server for authentication. The lack of encryption makes this an unsuitable
approach for Internet-based applications.
10 Module 5: Using HTTP to Access XML Data
Demonstration: Creating a Virtual Directory for SQL Server
*****************************ILLEGAL FOR NON-TRAINER USE******************************
In this demonstration, you will see how to use the SQL XML Support in IIS
tool to create a virtual directory that publishes Northwind Traders, a SQL
Server sample database.
You will then see how you can test IIS connectivity to the database by opening
the following URL in Internet Explorer:
http://localhost/northwind?sql=SELECT * FROM products FOR XML
AUTO&root=catalog
Topic Objective
To demonstrate how to
create a virtual directory for
SQL Server.
Lead-in
In this demonstration, you
will see how to create a
virtual directory for SQL
Server.
Delivery Tip
1. Start the Configure SQL
XML Support in IIS tool in
MMC.
2. Expand your server and
select Default Web Site.
3. Click Action, point to
New, and then click Virtual
Directory.
4. On the General tab, name
the virtual directory
Northwind, and then set
the path to the My
Documents folder.
5. Click Security, and then
click Use Windows
Integrated Authentication.
6. Click Data Source, and
select the Northwind
database on the (local)
server.
7. Click Settings, and then
select Allow sql=or
template= URL queries.
Point out to students that
Allow template queries is
already selected.
8. Show the remaining tabs
without changing them, and
then click OK.
9. Close the MMC window
and test the virtual directory
by using the URL provided
in the student notes on this
page.
Module 5: Using HTTP to Access XML Data 11
Testing HTTP Connectivity to SQL Server
Embedding SQL queries in the URL
Enable the virtual directory to accept URL queries
Include the sql parameter within the URL and specify the
XML root element
Specifying the root element that SQL will return
Explicitly concatenate the query with literal tags
Or, specify the XML root parameter
http://webserver/data?sql=SELECT
'<catalog>';SELECT productname,unitprice FROM products
FOR XML AUTO;SELECT '</catalog>'
http://webserver/data?sql=SELECT
'<catalog>';SELECT productname,unitprice FROM products
FOR XML AUTO;SELECT '</catalog>'
http://webserver/data?
sql=SELECT productname, unitprice FROM products
FOR XML AUTO;&root=catalog
http://webserver/data?
sql=SELECT productname, unitprice FROM products
FOR XML AUTO;&root=catalog
*****************************ILLEGAL FOR NON-TRAINER USE******************************
The easiest way to test access to SQL Server over HTTP is to embed a
Transact-SQL query in a URL that references a virtual directory. To enable IIS
to accept Transact-SQL queries embedded in URLs, you must select the Allow
URL queries option in the Configure SQL XML Support in IIS tool.
In production systems, the option to permit URL queries is usually disabled
because it presents a potential security risk for SQL Server. This is because the
SQL Administrator must apply a strict security model so that dangerous or
unauthorized queries will not be executed against the database. For production
systems, it is better to use a template file to run a specific query than to allow
URL queries.
Topic Objective
To describe how to create a
URL query to SQL Server.
Lead-in
The easiest way to test
access to SQL Server over
HTTP is to embed a
Transact-SQL query in a
URL.
12 Module 5: Using HTTP to Access XML Data
Embedding SQL Queries in the URL
You can embed a SQL query in a URL in two ways. First, the URL can contain
any valid Transact-SQL statement. Typically, these queries will make use of a
SELECTFOR XML statement. Second, the URL may contain a call to a
stored procedure to SQL Server or Open Database Connectivity (ODBC). In
either case, you must precede the query with the sql parameter within the URL.
In the following example, a URL contains a SELECTFOR XML statement:
http://localhost/northwind?sql=SELECT * FROM products FOR XML
AUTO&root=catalog
In the next example, a URL calls a stored procedure by using a Transact-SQL
statement or an ODBC Call syntax:
http://localhost/northwind?sql=EXEC CustOrdersOrders 'ALKFI'
http://localhost/northwind?sql={Call CustOrdersOrders }'ALKFI'
Specifying that the XML Result Is Well-Formed
To ensure that SQL Server returns a well-formed XML document, you specify
an XML root element in the URL. You can specify the XML root element in
one of two ways:
1. Explicitly concatenate the literal opening and closing tags to the SQL query.
The following URL could be used to retrieve product name and price data
within a catalog root element in a document in the data virtual directory of a
server named webserver:
http://webserver/data?sql=SELECT '<catalog>';SELECT productname,
unitprice FROM products FOR XML AUTO;SELECT '</catalog>'
2. Use the root parameter when executing the query.
The following URL retrieves the same data as in the previous example.
Because root is the second parameter in the URL, it is prefixed with an
ampersand (&):
http://webserver/data?sql=SELECT productid, unitprice FROM products
FOR XML AUTO&root=catalog
Example
Example
Module 5: Using HTTP to Access XML Data 13
Encoding URL Characters
Using Transact-SQL Characters in a URL
Original T-SQL that looks like this
must be encoded like this when it appears within a URL:
?sql=
SELECT+*+FROM+Orders+WHERE+CustomerID+LIKE+'G%25'+
FOR+XML+AUTO
&root=myresults
?sql=
SELECT+*+FROM+Orders+WHERE+CustomerID+LIKE+'G%25'+
FOR+XML+AUTO
&root=myresults
SELECT * FROM Orders WHERE CustomerID LIKE 'G%' FOR XML AUTO
SELECT * FROM Orders WHERE CustomerID LIKE 'G%' FOR XML AUTO
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Some Transact-SQL characters are not compatible with HTTP and must be
encoded when they are embedded in a URL.
Using Transact-SQL Characters in a URL
The following table shows characters that have special meaning in a URL, as
well as the appropriate encoding for these characters.
Transact-SQL
character
Meaning in Transact-SQL
Encode in a URL as:
+ Space %20
/ Directory separator %2F
? First parameter separator %3F
% Encoding escape character %25
# Bookmark indicator %23
& Additional parameter separator %26
Spaces are not permitted in a URL and should be indicated by using the
+ symbol or encoded as %20. Internet Explorer automatically converts
spaces in a URL to %20.
Topic Objective
To describe how to handle
special characters in a URL
query.
Lead-in
Some characters have
special meaning in a URL.
Note
14 Module 5: Using HTTP to Access XML Data
Publishing XML Templates on the Server
Creating XML Template Files
Publishing a Template Virtual Name
Demonstration: Publishing an XML Template
Using Parameters in Template Files
Applying a Style Sheet to a Template File
*****************************ILLEGAL FOR NON-TRAINER USE******************************
In a production environment, one of the main problems with URL queries is
that the database schema is exposed to the client application. To avoid this, you
can create XML templates on the server that retrieve specific data and return it
as XML or HTML to the client. In this solution, the client only receives the
query results, and the developer has much greater control over the data that is
published.
This section discusses the creation and use of XML template files.
Topic Objective
To introduce the topics in
this section.
Lead-in
XML templates provide a
way to publish data without
providing direct access to
the database.
Module 5: Using HTTP to Access XML Data 15
Creating XML Template Files
Compared to URL queries, template files are:
More secure and easier to maintain because they are
stored on the server
Flexible because they can accept parameters
A template file consists of a valid XML document that
contains one or more SQL statements or XPath queries
<?xml version="1.0"?>
<catalog xmlns:sql='urn:schemas-microsoft-com:xml-sql'>
<sql:query>
SELECT productid, productname, unitprice
FROM products product
FOR XML AUTO
</sql:query>
</catalog>
<?xml version="1.0"?>
<catalog xmlns:sql='urn:schemas-microsoft-com:xml-sql'>
<sql:query>
SELECT productid, productname, unitprice
FROM products product
FOR XML AUTO
</sql:query>
</catalog>
*****************************ILLEGAL FOR NON-TRAINER USE******************************
A template file is a valid XML document stored on the Web server that contains
one or more SQL statements and XPath queries. It is better to store your queries
in template files rather than encode them in URLs, primarily because it is easier
to maintain and secure queries when you store them on the server. Another
good reason to use template files is that you can include one or more query
parameters in the URL that calls the template file, thus increasing the template
files flexibility.
Creating an XML Template File
You can create an XML template by using Microsoft Notepad or any other text
editor.
In the XML document, you represent each query in a separate <query> element.
Each <query> element may contain either a FOR XML query or a call to a
stored procedure.
When an HTTP client requests a URL that references a template file,
SQL Server processes each of the queries in the template file and returns the
results as XML fragments. The resulting XML document is then sent to the
client.
The following text could be saved as a template file named catalog.xml and
used to retrieve product information:
<?xml version="1.0"?>
<catalog xmlns:sql='urn:schemas-microsoft-com:xml-sql'>
<sql:query>
SELECT productid, productname, unitprice
FROM products product
FOR XML AUTO
</sql:query>
</catalog>
Topic Objective
To describe how an XML
template file is created.
Lead-in
A template file consists of a
valid XML document that
contains one or more SQL
statements or XPath
queries.
Delivery Tip
Point out that the XML
documents in template files
are the same as the XML
templates submitted by
using ADO. The main
difference is that template
files are typically stored on
the server instead of being
defined on the client.
Example
16 Module 5: Using HTTP to Access XML Data
Publishing a Template Virtual Name
Assign virtual names to folders containing template files
Users include the virtual name in a URL
http://webserver/data/templates/catalog.xml
http://webserver/data/templates/catalog.xml
C:\SQLSite
C:\Templates
C:\Templates\catalog.xml
Web server
Object Physical path Name
Virtual directory
Virtual name
Template file
data
templates
webserver
catalog.xml
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Template files can be saved in any folder on the Web server. They do not need
to be in the same directory tree as the virtual directory. To allow a template file
to be accessed via a URL, the folder that contains the template file must be
configured in IIS as a virtual name of the Template type.
Configuring a Template Virtual Name
You use the Configure SQL XML Support tool in IIS to assign a virtual name
to a folder that contains a template file. Consider the following facts and
guidelines when assigning a virtual name to the folder that contains a template
file:
Each virtual name must be unique within the virtual directory application.
A virtual name may contain a hierarchy of subfolders.
You must assign appropriate file system permissions to the folder
referenced by the virtual name, and to its subfolders and files, so that the
template files can be read. The account that needs to be granted permissions
will depend on the security model that you are using on the virtual directory.
Specifying a Virtual Name in a URL
A URL that uses a template file follows this syntax:
http://domain/virtualdirectory/virtualname/[subfolder/..]template
In this example, the URL accesses a template named catalog.xml in a virtual
name called templates, located in a virtual directory named data on a Web
server named webserver:
http://webserver/data/templates/catalog.xml
Topic Objective
To describe how template
virtual names are created
and used.
Lead-in
Template files are saved in
a folder that is configured as
a virtual name.
Example
Module 5: Using HTTP to Access XML Data 17
Demonstration: Publishing an XML Template
*****************************ILLEGAL FOR NON-TRAINER USE******************************
In this demonstration, you will see how a template can be used to retrieve data
from the Northwind Traders database.
The following template will be saved as catalog.xml in a virtual name called
Templates, and will be accessed by using a browser:
<?xml version="1.0"?>
<catalog xmlns:sql='urn:schemas-microsoft-com:xml-sql'>
<sql:query>
SELECT productid, productname, unitprice
FROM products product
FOR XML AUTO
</sql:query>
</catalog>
The template will be accessed by using the following URL:
http://localhost/northwind/templates/catalog.xml
Topic Objective
To demonstrate how to
publish an XML template on
IIS, and how the XML
template can be called from
a URL.
Lead-in
In this demonstration, you
will see how an XML
template is published and
used.
This demonstration requires
an existing virtual directory
named Northwind. If you did
not complete the previous
demonstration, run
CreateNWind.vbs in the
folder DemoCode\Mod05.
1. Copy the Templates
folder from
DemoCode\Mod05 into the
My Documents folder.
2. Start the Configure SQL
XML Support in IIS tool.
3. Expand your server and
select Default Web Site.
4. Double-click the
Northwind virtual directory,
and then click Settings.
5. Point out that template
queries are allowed.
6. Click Virtual Names, and
then click New.
7. Create a virtual name
called templates with a
type of template and a
path to the Templates folder
you copied into My
Documents. Click Save, and
then click OK.
8. Close the Microsoft
Management Console
window and test the
template with the URL
provided in the student
notes on this page.
18 Module 5: Using HTTP to Access XML Data
Using Parameters in Template Files
Specify any parameters in the template header
Prefix the parameter with @ in the query
<?xml version="1.0"?>
<catalog xmlns:sql='urn:schemas-microsoft-com:xml-sql'>
<sql:header>
<sql:param name="category">1</sql:param>
</sql:header>
<sql:query>
SELECT productid, productname, unitprice
FROM products product
WHERE categoryid = @category
FOR XML AUTO
</sql:query>
</catalog>
<?xml version="1.0"?>
<catalog xmlns:sql='urn:schemas-microsoft-com:xml-sql'>
<sql:header>
<sql:param name="category">1</sql:param>
</sql:header>
<sql:query>
SELECT productid, productname, unitprice
FROM products product
WHERE categoryid = @category
FOR XML AUTO
</sql:query>
</catalog>
*****************************ILLEGAL FOR NON-TRAINER USE******************************
In a template file, a parameter is a variable within the query string whose value
is provided by the user. Using parameters makes template files more flexible.
Specifying Parameters in a Template Header
All parameters must be specified within the <sql:header> element. Consider the
following facts about template parameters:
All parameters for a template must be contained within a single
<sql:header> element.
Use a separate <sql:param> element to specify each parameter.
For each <sql:param> element you create, you must supply a name attribute
that is unique within the template.
Assign each parameter a default value by using the element value.
Referencing Parameters in a Query
You reference parameters in queries by prefixing the name of the parameter
with the @ symbol. For example, a parameter named category could be
referenced in a query as @category.
Using Comparison Operators in a Parameter
You can make a parameter more flexible by including comparison operators,
such as greater than or less than. When you use comparison operators, you
must encode any characters that have specific meanings in XML. For example,
the greater than operator must be encoded as >, and the less than
operator as <.
Topic Objective
To describe how to add one
or more parameters to a
template.
Lead-in
You make your templates
more flexible if you add one
or more parameters.
Module 5: Using HTTP to Access XML Data 19
Passing Parameters in a URL
Parameters are passed in a URL as a query string. The first parameter is
indicated by using a question mark (?), and subsequent parameters are separated
by using an ampersand (&).
The following URL could be used to pass category and price parameters to a
template called catalog.xml:
http://webserver/data/templates/catalog.xml?category=1&price=1
1.99
The next example shows an XML template that accepts category and price
parameters. Note that the greater than operator > has been encoded in the
SELECT statement:
<?xml version="1.0"?>
<catalog xmlns:sql='urn:schemas-microsoft-com:xml-sql'>
<sql:header>
<sql:param name="category">1</sql:param>
<sql:param name="price">0</sql:param>
</sql:header>
<sql:query>
SELECT productid, productname, unitprice
FROM products product
WHERE categoryid = @category
AND unitprice > @price
FOR XML AUTO
</sql:query>
</catalog>
To pass NULL as a parameter, you must install the XML for SQL Web
Release and create a nullvalue attribute in the header element. This allows you
to specify a string constant that will be interpreted as NULL when passed to a
template.
Example
Note
20 Module 5: Using HTTP to Access XML Data
Applying a Style Sheet to a Template File
Server-side XSL processing
Client-side XSL processing
<?xml version="1.0"?>
<catalog xmlns:sql='urn:schemas-microsoft-com:xml-sql'
sql:xsl="catalog.xsl">
<sql:query>
...
</sql:query>
</catalog>
<?xml version="1.0"?>
<catalog xmlns:sql='urn:schemas-microsoft-com:xml-sql'
sql:xsl="catalog.xsl">
<sql:query>
...
</sql:query>
</catalog>
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="catalog.xsl"?>
<catalog xmlns:sql='urn:schemas-microsoft-com:xml-sql'>
<sql:query>
...
</sql:query>
</catalog>
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="catalog.xsl"?>
<catalog xmlns:sql='urn:schemas-microsoft-com:xml-sql'>
<sql:query>
...
</sql:query>
</catalog>
*****************************ILLEGAL FOR NON-TRAINER USE******************************
By default, executing a query by using a template file returns XML. However,
it is also possible to render the data in a different format such as HTML or the
Website META Language. To do this, you can apply one or more Extensible
Stylesheet Language (XSL) style sheets to a template file.
You can apply a style sheet at the server, the client, or both. When style sheets
are applied at both the client and the server, the server-side style sheet is applied
first, and then the client processes the results.
Choosing Whether to Process at the Server or the Client
The advantage to server-side processing is that your XSL style sheet will be run
regardless of the type of browser making the request. The disadvantage to
server-side processing is the additional load that it places on the server.
Client-side XSL processing should be reserved for use in intranet environments
where the Web browser is known to support XSL processing, as in
Internet Explorer. Relying on client-side XSL processing in an Internet-based
solution will limit the number of users who can successfully browse your site.
Applying a Style Sheet on the Server
To apply a style sheet on the server, add a sql:xsl attribute to the templates root
element. This attribute should reference a style sheet in a relative path to the
virtual name that contains the template.
Topic Objective
To describe how a style
sheet can be applied to a
template.
Lead-in
You can apply XSL style
sheets to XML templates.
Module 5: Using HTTP to Access XML Data 21
The following template includes a sql:xsl attribute.
<?xml version="1.0"?>
<catalog xmlns:sql='urn:schemas-microsoft-com:xml-sql'
sql:xsl="catalog.xsl">
<sql:header>
<sql:param name="category">1</sql:param>
</sql:header>
<sql:query>
SELECT productname, unitprice
FROM products product
WHERE categoryid = @category
FOR XML AUTO
</sql:query>
</catalog>
Specifying the Content Type of Returned Data
By default, SQL Server returns data requests from virtual directories in text or
XML format. If you use a server-side style sheet to transform the document into
a different content type, you must specify the appropriate contenttype parameter
in the URL.
The following URL retrieves data from a template named catalog.xml that has
been transformed into HTML by a server-side style sheet:
http:/webserver/data/templates/catalog.xml?category=1&contentt
ype=text/html
Specifying a Client-Side Style Sheet
When you use an XML-aware client such as Internet Explorer, you can add a
processing instruction to the template that specifies a style sheet to be applied
by the client. XML-aware clients will parse the XML document that contains
the processing instruction and download the specified style sheet before
applying it to the XML. Client applications that are not XML-aware will simply
receive the XML results, and might need custom code in order to process the
data.
Example
Example
22 Module 5: Using HTTP to Access XML Data
The following template includes a processing instruction for the client to apply
a style sheet. Because the client expects to receive an XML document, there is
no requirement to specify the content type in the URL.
<?xml version="1.0"?>
<?xml-stylesheet type='text/xsl' href='catalog.xsl'?>
<catalog xmlns:sql='urn:schemas-microsoft-com:xml-sql'>
<sql:header>
<sql:param name="category">1</sql:param>
</sql:header>
<sql:query>
SELECT productname, unitprice
FROM products product
WHERE categoryid = @category
FOR XML AUTO
</sql:query>
</catalog>
Example
Module 5: Using HTTP to Access XML Data 23
Lab 5.1: Publishing a SQL Server Database
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Objectives
After completing this lab, you will be able to:
Create an IIS virtual directory for a SQL Server database.
Test a virtual directory by using URL queries.
Create and use XML templates to retrieve XML data over HTTP.
Prerequisites
Before working on this lab, you must have:
Knowledge of IIS virtual directories.
Knowledge of how to use the MMC tool Configure SQL XML Support in
IIS.
For More Information
Read the section Accessing SQL Server Using HTTP in SQL Server Books
Online.
Scenario
Northwind Traders wants to publish its catalog on the Internet. In this lab, you
will create a virtual directory for the Northwind database and test it by using
URL queries.
Estimated time to complete this lab: 45 minutes
Topic Objective
To introduce the lab.
Lead-in
In this lab, you will create
and use XML templates in a
virtual directory that
references a
SQL Server 2000 database.
Explain the lab objectives.
24 Module 5: Using HTTP to Access XML Data
Exercise 1
Creating a Virtual Directory
In this exercise, you will use the Configure SQL XML Support in IIS tool to
create a virtual directory that allows HTTP access to the Northwind database.
Scenario
The first step in publishing the Northwind Traders catalog on the Internet is to
create an IIS virtual directory that can be used to access the Northwind
database.
To create a new SQL Server virtual directory
1. In the Microsoft SQL Server program group, open Configure SQL XML
Support in IIS.
2. Expand your server and select Default Web Site.
3. Click Action, point to New, and then click Virtual Directory.
4. On the General tab, configure the following settings.
Setting Value
Virtual Directory Name Lab05
Local Path <install folder>\Labs\Lab05\
Northwindweb
5. Click Security, and then click Use Windows Integrated Authentication.
6. Click Data Source and configure the following settings.
Setting Value
SQL Server (local)
Database Northwind
7. Click Settings and select the necessary options to allow URL (sql=)
queries and template queries.
8. Click OK to close the dialog box and create the virtual directory.
9. Close the IIS Virtual Directory Management for SQL Server window.
To view the virtual directory with Internet Services Manager
1. In the Administrative Tools program group, start Internet Services
Manager.
2. In the left pane, expand your server, and then open Default Web Site. Note
that Lab05 is listed among the Web applications.
3. Close Internet Services Manager.
Module 5: Using HTTP to Access XML Data 25
Exercise 2
Testing the Virtual Directory Using URL Queries
In this exercise, you will test the Lab05 virtual directory by submitting URL
queries.
Scenario
To test HTTP connectivity, you can execute queries by submitting them in a
URL.
To execute a URL query including an explicit root element
1. In Internet Explorer, type the following URL and examine the resulting
document:
http://localhost/lab05?sql=SELECT '<pricelist>';
SELECT productname, unitprice FROM products
FOR XML AUTO; SELECT '</pricelist>'
2. Edit the URL to return a document with a top-level element named
<catalog>.
To execute a URL query by using the root parameter
Enter a new URL query that retrieves the productid, productname, and
unitprice fields from the products table. Use a root parameter to create a
directory element named <catalog>.
To execute a query containing encoded characters
Enter a URL query that returns a document with a top-level element named
<catalog> by using the following SQL query. Encode any characters that
have special meaning in a URL.
SELECT productid, productname, unitprice
FROM products product
WHERE productname LIKE 'C%
FOR XML AUTO
26 Module 5: Using HTTP to Access XML Data
Exercise 3
Creating a Template Virtual Name
In this exercise, you will create a template virtual name that will be used to
store templates.
Scenario
Northwind Traders wants users to be able to browse its catalog by using
templates. To make this possible, a template virtual name must be created to
host the template files.
To create a virtual name for the templates folder
1. Start the Configure SQL XML Support in IIS tool.
2. Expand your server and select Default Web Site.
3. Open Lab05 to view its properties.
4. Click Settings and ensure that the option to allow template queries is
selected.
5. Click Virtual Names, and then click New.
6. Create a new virtual name with the following configuration.
Setting Value
Virtual name: templates
Type: template
Path: <install folder>
\Labs\Lab05\Northwindweb\Templates
7. Click Save to create the virtual name, and then click OK to close the dialog
box.
8. Close the IIS Virtual Directory Management for SQL Server window.
Module 5: Using HTTP to Access XML Data 27
Exercise 4
Creating Templates
In this exercise, you will create templates to retrieve data from the Northwind
Traders database.
Scenario
Users of the Northwind Traders Web site must be able to browse products by
category. This requires the creation of two templates: one to list the categories,
and another to list the products in a specified category.
To create a template containing a Transact-SQL query
The file Categories.xml in the folder <install folder>\Labs\Lab05\Solution
contains a solution to this procedure.
1. Open Notepad and create an XML template with the following
characteristics:
The root element should be named <categorylist>.
The root element should contain the following attribute declaration:
xmlns:sql="urn:schemas-microsoft-com:xml-sql"
The template should contain a <sql:query> element.
The <sql:query> element should contain the following query:
SELECT categoryid, categoryname, picture
FROM categories category
FOR XML AUTO
2. Save the template as categories.xml in the folder <install folder>\
Lab05\Northwindweb\Templates.
3. Test your template by opening
http://localhost/lab05/templates/categories.xml in Internet Explorer. Internet
Explorer should be able to open an XML document that contains
<category> elements.
28 Module 5: Using HTTP to Access XML Data
To create a parameterized template
The file Products.xml in the folder <install folder>\Labs\Lab05\Solution
contains a solution to this procedure.
1. In Notepad, create an XML template with the following characteristics:
Name the root element <productlist>. It should contain the xml-sql
namespace attribute.
The template should contain a parameter named category with a
default value of 1.
The template should contain a query that returns the productid,
productname, and unitprice of each row in the products table where
the categoryid matches the template parameter. Each row returned by the
query should result in a <product> element.
2. Save the template as products.xml in the folder <install folder>\
Lab05\Northwindweb\Templates.
3. Test your template by opening
http://localhost/lab05/templates/products.xml?category=4 with
Internet Explorer. Internet Explorer should be able to open an XML
document containing <product> elements.
Module 5: Using HTTP to Access XML Data 29
Exercise 5
Applying Style Sheets
In this exercise, you will edit the categories.xml and products.xml templates so
that a style sheet is applied to the results.
Scenario
To make the Northwind Traders product data available to users through a
browser, XSL style sheets must be applied to the templates to render the data as
HTML.
To add a style sheet reference to categories.xml
The file CategoriesEX5.xml in the folder <install folder>\Labs\Lab05\Solution
contains a solution to this procedure.
1. Open the file categories.xml with Notepad from the folder Lab05\Starter.
2. Modify the template so that categories.xsl will be applied on the server.
3. Save the template to <install folder>\Lab05\Northwindweb\Templates.
To add a style sheet reference to products.xml
The file ProductsEX5.xml in the folder <install folder>\Labs\Lab05\Solution
contains a solution to this procedure.
Repeat the preceding procedure to configure the products.xml file to
reference the products.xsl style sheet.
To test your templates
1. Open the template categories.xml in Internet Explorer. You will need to
include an appropriate contenttype parameter in the URL.
2. When the category list is displayed, click any link on the page to view the
products in that category.
30 Module 5: Using HTTP to Access XML Data
Posting Query Templates from the Client
Enabling POST Queries
Using an HTML Form to Post a Template
Posting Templates Directly to the Virtual Directory
Demonstration: Posting a Template
*****************************ILLEGAL FOR NON-TRAINER USE******************************
POST is an HTTP method that allows you to send data to a server with an
HTTP request. The POST method is commonly used on Web pages that
contain forms in which a user enters data and then clicks a Submit button to
send the data to the server. SQL Server allows you to send XML templates to
the server in this way.
In some circumstances, you might want to allow templates to be sent by a client
application by using the HTTP POST method. This section describes the
necessary configuration and development tasks for using queries that
incorporate the POST method. Such queries will be referred to as POST
queries.
Topic Objective
To introduce the topics in
this section.
Lead-in
Templates can be posted
from a client application
over HTTP.
Module 5: Using HTTP to Access XML Data 31
Enabling POST Queries
Configuring application settings
Allow URL queries and POST queries
Specify a maximum POST length
Consider security issues carefully
*****************************ILLEGAL FOR NON-TRAINER USE******************************
You can use the MMC tool Configure SQL XML Support in IIS to allow POST
queries.
Configuring Application Settings
POST templates are configured on the Settings tab of the New Virtual
Directory Properties dialog box. You can configure POST queries by setting
the following options:
Allow SQL= Queries
Allow POST Queries
Set the maximum size in bytes of a POST query
To allow templates to be posted, both URL queries and POST queries must be
enabled.
Security Considerations
You should consider potential security risks when deciding whether to allow
POST queries. Keep in mind that any user who can make an HTTP connection
to the virtual directory can send a template containing any valid SQL query.
Also consider that, because you must enable URL queries, users can execute
any SQL statement by adding it to the URL.
Any database object permissions that you have set will be enforced, allowing
you to prevent access to sensitive data. However, in most Internet-based
solutions, you should restrict data access to the maximum extent possible. For
this reason, allowing POST templates is not recommended in production
Internet sites.
Topic Objective
To describe the
configuration necessary to
allow POST queries.
Lead-in
The Configure SQLXML
Support in IIS tool can be
used to allow POST queries.
Delivery Tip
The option to allow SQL=
queries appears in the user
interface as Allow URL
Queries unless the XML for
SQL Web Release has been
installed.
32 Module 5: Using HTTP to Access XML Data
Using an HTML Form to Post a Template
Add a FORM tag containing a template to a Web page
Set Action attribute to the virtual directory URL
Set Method attribute to POST
Specify template in a hidden INPUT field named template
Use INPUT fields for parameters
Field names and parameter names must match
Default content type is HTML
Use a hidden INPUT field named xsl to specify a style sheet
Use a hidden INPUT field named contenttype to specify
text/xml
*****************************ILLEGAL FOR NON-TRAINER USE******************************
You can post a template from a Web page by using an HTML form. Forms are
a common way to post data from a Web page to a Web server.
Adding a FORM Containing a Template to a Web Page
You specify a form on a Web page by using the <FORM> HTML tag. To post
the form to a virtual root SQL Server, you must include the following attributes.
FORM attribute Value
Action URL of the virtual directory
Method POST
HTML forms generally contain tags such as <INPUT>, which create fields to
allow users to enter data. The data is then appended as a query string to the
URL specified in the Action attribute, and sent to the server when the user
clicks a Submit button.
The template containing the query to be executed should be specified in an
INPUT field with the following attributes.
INPUT attribute Value
Type hidden
Name template
Value The XML template as a string
Because the template field is hidden, users will not see the template text on the
Web page. However, users will be able to read the template definition by
viewing the pages HTML source.
Topic Objective
To describe how an HTML
form can be used to post a
template.
Lead-in
You can post XML
templates from a Web page
by using an HTML form.
Module 5: Using HTTP to Access XML Data 33
Using INPUT Fields for Query Parameters
If the template contains parameters, you can use INPUT fields to allow users to
set the values to be passed to the template. The name attribute for each INPUT
field must match the corresponding parameter name in the template.
INPUT fields for parameter values should be assigned a type attribute that
allows user input, such as text. Additionally, the value attribute may be set to
a default parameter value to allow users to accept a default choice.
Managing the Content Type
The default content type for templates posted from a Web form is text/html.
Typically, you will want the data returned to the browser by the query to be
formatted as HTML by using a server-side style sheet. You can specify which
style sheet to apply to the data by including a hidden INPUT field with a name
attribute of xsl and a value attribute indicating the relative path of the style
sheet. The style sheet path must be relative to the virtual directory on the Web
server.
Alternatively, you might want the results to be sent to the browser as XML. To
do so, you can include a hidden INPUT field with a name attribute of
contenttype and a value attribute of text/xml.
The following example shows an HTML page that contains a template in a
FORM tag. The template contains a parameter, and the results will be returned
as HTML by applying a style sheet named catalog.xsl.
<HTML><HEAD><TITLE>Request Catalog</TITLE></HEAD>
<BODY>
Enter a Category ID.
<FORM action="http://webserver/data" method="POST">
<B>Category ID</B>
<INPUT type=text name=category value='1'>
<INPUT type=hidden name=xsl value='catalog.xsl'>
<INPUT type=hidden name=template value='
<catalog xmlns:sql="urn:schemas-microsoft-com:xml-sql" >
<sql:header>
<sql:param name="category">1</sql:param>
</sql:header>
<sql:query>
SELECT productid, productname, unitprice
FROM products product
WHERE categoryID=@category
FOR XML AUTO
</sql:query>
</catalog>
'>
<p><INPUT type="submit">
</FORM>
</BODY></HTML>
Example
34 Module 5: Using HTTP to Access XML Data
Posting Templates Directly to the Virtual Directory
Load the template into a DOM document
Post the DOM document to the virtual directory
Set objDoc = CreateObject("Microsoft.XMLDom")
Set objhttp = CreateObject("Microsoft.xmlhttp")
objDoc.LoadXML strTemplate
objhttp.Open "POST", "http://webserver/data", False
objhttp.Send objDoc
Msgbox objhttp.ResponseText
Set objDoc = CreateObject("Microsoft.XMLDom")
Set objhttp = CreateObject("Microsoft.xmlhttp")
objDoc.LoadXML strTemplate
objhttp.Open "POST", "http://webserver/data", False
objhttp.Send objDoc
Msgbox objhttp.ResponseText
*****************************ILLEGAL FOR NON-TRAINER USE******************************
There might be situations where a code component needs to post an XML query
template to a SQL Server virtual directory. For example, a business component
written in Microsoft Visual Basic might need to retrieve product data in XML
format.
Templates can be posted programmatically by using the Microsoft XML 3.0
component library (MSXML3.dll).
Loading a Template into a DOM Document
The first step in posting a template by using the MSXML components is to load
the template into a Document Object Model (DOM) document object.
The template can be loaded from a string variable by using the LoadXML
method, or from a file by using the Load method. When using the Load
method, it is important to first set the Async property to False; otherwise your
code might begin processing the XML before the entire XML document has
been fully loaded and parsed.
When the document is loaded, you should use the MSXML parser to validate
the XML before further processing. You can do this by checking the
parseError.errorCode property for any value other than 0.
Posting the DOM Document
After the template is loaded into a DOM document, the object can be posted to
the virtual directory by using the XMLHTTP object. There are three steps
required to post an XML template by using the XMLHTTP object:
1. Use the Open method to open a connection to the virtual directory,
specifying POST as the HTTP method you want to use.
2. Use the Send method to submit the template to the virtual directory.
3. Use the ResponseText property to retrieve the query results.
Topic Objective
To describe how templates
can be posted directly to the
virtual directory.
Lead-in
Templates can also be
posted to a virtual directory
programmatically.
Module 5: Using HTTP to Access XML Data 35
This example shows a Visual Basic script that could be used to post a template
to SQL Server:
Dim objDoc
Dim objHTTP
Dim strTemplate
Set objDoc = CreateObject("Microsoft.xmldom")
Set objHTTP = CreateObject("Microsoft.xmlhttp")
' create the template
strTemplate = "<?xml version='1.0'?>" & _
"<catalog xmlns:sql='urn:schemas-microsoft-com:xml-sql'>" & _
"<sql:query >" & _
" SELECT productid, productname FROM products FOR XML RAW" & _
"</sql:query>" & _
"</catalog>"
' Validate the document using the MSXML parser.
objDoc.loadXML strTemplate
If doc.parseError.errorCode Then
MsgBox "The template is invalid"
' Post the template.
Else
objHTTP.Open "POST", "http://webserver/data", False
objHTTP.send objDoc
' Retrieve the results.
MsgBox objHTTP.responseText
End If
Example
36 Module 5: Using HTTP to Access XML Data
Demonstration: Posting a Template
*****************************ILLEGAL FOR NON-TRAINER USE******************************
In this demonstration, you will see how to configure a virtual directory to allow
POST templates. You will see an example of a template posted from an HTML
form, and an example of a template posted programmatically by using the
Microsoft XML components.
Topic Objective
To demonstrate how to post
a template.
Lead-in
In this demonstration, you
will see how a template can
be posted to a SQL Server
virtual directory.
This demonstration requires
an existing virtual directory
named Northwind. If you did
not complete the previous
demonstration, run
CreateNWind.vbs from the
folder DemoCode\Mod05.
1. Start the Configure SQL
XML Support in IIS tool.
2. Expand your server and
select Default Web Site.
3. Double-click Northwind
and select the Settings tab.
4. Point out that, Allow
SQL=or template=URL
queries, is already selected.
Select Allow POST, click
OK, and then close the
MMC.
5. Use Notepad to show the
contents of the post.htm file
in the folder
DemoCode\Mod05.
6. Copy catalog.xsl to My
Documents.
7. Open post.htm in Internet
Explorer. Enter 4 as the
category ID, and click
Submit Query to view the
results.
8. In Notepad, show the
contents of post.vbs.
9. Close Notepad and
double-click post.vbs to
execute it.
Module 5: Using HTTP to Access XML Data 37
Publishing a Database Object
Creating a dbobject Virtual Name
Retrieving an Object over HTTP
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Databases are often used to store binary data such as images. This binary data
can be retrieved through a SQL Server virtual directory by using a dbobject
virtual name.
This section discusses the creation and use of a dbobject virtual name.
Topic Objective
To introduce the topics in
this section.
Lead-in
Binary objects such as
images can be retrieved by
using a dbobject virtual
name.
38 Module 5: Using HTTP to Access XML Data
Creating a dbobject Virtual Name
Create a dbobject virtual name to retrieve BLOB data
(for example, an image)
Name the virtual name dbobject to match the default
for binary objects returned in AUTO mode
No path is specified
Only one dbobject virtual name is required for each
virtual directory
Allow XPath queries
*****************************ILLEGAL FOR NON-TRAINER USE******************************
To publish binary large object (BLOB) data in a SQL Server virtual directory,
you must create a dbobject virtual name.
Creating a dbobject Virtual Name for BLOB Data
Similar to template virtual names, you create dbobject virtual names by using
the Configure SQL XML Support in IIS tool. Consider the following
configuration issues when creating a dbobject virtual name:
If you name the virtual name dbobject, the paths used to retrieve binary
data items will be consistent with the paths returned by AUTO mode queries
that include binary fields.
No file path is specified for dbobject virtual names.
A single dbobject virtual name allows access to any binary data in the
published database. You only need to create one dbobject virtual name in a
virtual directory to allow access to all dbobjects.
Allowing XPath Queries
To access objects by using a dbobject virtual name, XPath queries must be
allowed in the virtual directory. To enable XPath queries, select the Allow
XPath check box on the Settings tab of the Properties dialog box for the
virtual directory.
Topic Objective
To describe how to create a
dbobject virtual name.
Lead-in
To publish binary objects
over HTTP, you must create
a dbobject virtual name.
Module 5: Using HTTP to Access XML Data 39
Retrieving an Object over HTTP
Specify an XPath to identify a single column / single value
In style sheets that use AUTO mode templates, use the
dbobject path as the source for IMAGE fields
dbobject/categories[@categoryid='1']/@picture
dbobject/categories[@categoryid='1']/@picture
<IMG>
<xsl:attribute name='SRC'>
http://webserver/data/
<xsl:value-of select='@picture'/>
</xsl:attribute>
</IMG>
<IMG>
<xsl:attribute name='SRC'>
http://webserver/data/
<xsl:value-of select='@picture'/>
</xsl:attribute>
</IMG>
*****************************ILLEGAL FOR NON-TRAINER USE******************************
You can only use a dbobject virtual name to retrieve a single binary value, such
as a single image.
Specifying an XPath for a Single Column/Single Value
A primary key value is usually specified in an XPath to retrieve a single
column/single value result set through a dbobject virtual name. The XPath must
specify the table containing the data, a unique identifier for the row, and the
name of the binary field to be retrieved, in an attribute-centric format.
The following XPath could be used to retrieve the picture field for the row in
the categories table with a categoryid value of 1:
categories[@categoryid='1']/@picture
To retrieve the data over HTTP, the XPath is appended to the URL for the
dbobject virtual name as follows:
http://webserver/data/dbobject/categories[@categoryid='1']/@pi
cture
Topic Objective
To describe how to retrieve
binary data by using a
dbobject virtual name.
Lead-in
You must specify a single
binary field when retrieving
data by using a dbobject
virtual name.
Example
40 Module 5: Using HTTP to Access XML Data
Using a dbobject Path in an XSL Style Sheet
You can use a dbobject path in an XSL style sheet to retrieve images and
display them in an HTML <IMG> tag.
You use an AUTO mode query to retrieve data from a table that includes a
dbobject path. This technique requires you to include the primary key field in
the query. You can then apply a style sheet to this data.
The style sheet that you apply should create an <IMG> tag for each row
returned by the query that has a SRC attribute constructed from the URL of the
virtual directory and the dbobject path returned by the query. When the page is
rendered, the dbobject path is used to retrieve the individual images and display
them on the HTML page.
The following template could be used to retrieve a list of category IDs, category
names, and pictures:
<?xml version="1.0"?>
<catalog xmlns:sql="urn:schemas-microsoft-com:xml-sql"
sql:xsl="catalog.xsl">
<sql:query>
SELECT categoryid, categoryname, picture
FROM categories category
FOR XML AUTO
</sql:query>
</catalog>
The query in this template would return an XML document similar to the
following:
<catalog xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<category categoryid="1"
categoryname="Beverages"
picture="dbobject/categories[@categoryid='1']/@picture"/>
<category categoryid="2"
categoryname="Condiments"
picture="dbobject/categories[@categoryid='2']/@picture"/>
</catalog>
Example
Module 5: Using HTTP to Access XML Data 41
The catalog.xsl style sheet could be used to create an <IMG> tag for each
category with a SRC attribute specifying the appropriate dbobject path to the
image. The SRC attribute is created by using the <xsl:attribute> tag, as shown
in the following example:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<HTML><TITLE>Catalog</TITLE><BODY>
<xsl:for-each select="catalog/category">
<IMG>
<xsl:attribute name="SRC">
http://webserver/data/<xsl:value-of select="@picture"/>
</xsl:attribute>
</IMG>
<BR/>
<B><xsl:value-of select="@categoryname"/></B>
<BR/>
<BR/>
</xsl:for-each>
</BODY>
</HTML>
</xsl:template>
</xsl:stylesheet>
Example
42 Module 5: Using HTTP to Access XML Data
Lab 5.2: Accessing a Database Object
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Objectives
After completing this lab, you will be able to access database objects
over HTTP.
Prerequisites
Before working on this lab, you must have:
Knowledge of how to create a virtual name in a virtual directory for a
SQL Server database.
Knowledge of how to retrieve a database object by using a dbobject virtual
name and an XPath query.
For More Information
Read the section Accessing SQL Server using HTTP in SQL Server Books
Online.
Scenario
Northwind Traders wants to use images on its Web site. These images are
stored as binary objects in the database.
Estimated time to complete this lab: 15 minutes
Topic Objective
To introduce the lab.
Lead-in
In this lab, you will access
binary data by using a
dbobject virtual name.
Explain the lab objectives.
Module 5: Using HTTP to Access XML Data 43
Exercise 1
Creating a Virtual Name for a dbobject
In this exercise, you will create a dbobject virtual name to allow access to
images in the Northwind database over HTTP.
Scenario
Each category in the Northwind Traders catalog has an associated image. The
images are stored in the Northwind database. You must create a dbobject virtual
name so that the images can be retrieved by using HTTP.
To create a dbobject virtual name
1. If you did not complete Lab 5.1, run the script SkipLab51.vbs from the
folder <install folder>\Labs\Lab05.
2. Start the Configure SQL XML Support in IIS tool from the Microsoft
SQL Server program group.
3. Expand your server and select Default Web Site.
4. Open Lab05 to view its properties.
5. Click Settings, and then select Allow XPath.
6. Click Virtual Names, and then click New.
7. Create a new virtual name with the following configuration.
Setting Value
Virtual name: dbobject
Type: dbobject
8. Click Save to create the virtual name, and then click OK.
9. Close IIS Virtual Directory Management for SQL Server.
44 Module 5: Using HTTP to Access XML Data
Exercise 2
Retrieving Image Data over HTTP
In this exercise, you will test your dbobject virtual name by retrieving image
data over HTTP.
Scenario
The images associated with each category in the Northwind Traders catalog
must be displayed on the Web page. To achieve this, you must retrieve the
images by using the dbobject virtual name.
To retrieve image data over HTTP
1. Open Internet Explorer and enter a URL that includes the following
information:
The path to the dbobject virtual name in the Lab05 virtual directory
An XPath specifying the picture columns for the row in the categories
table where the categoryid column has the value 3
2. View the image.
3. Retrieve the image where the categoryid column has the value 4.
4. Close Internet Explorer.
To reference image data in a style sheet
The file Categories(with IMG).xsl in the folder <install folder>\
Labs\Lab05\Solution contains a solution to this procedure.
1. Open the file categories.xsl with Notepad from the folder
<install folder>\Labs\Lab05\Starter.
2. Find the comment <!-- Add code to display picture here -->.
3. Under this comment, add the necessary XSL code to create an <IMG> tag
with a SRC attribute referencing the current picture field.
4. Save the style sheet to<install folder>\
Lab05\Northwindweb\Templates and close Notepad.
5. In Internet Explorer, test your style sheet by navigating to:
http://localhost/lab05/templates/categories.xml?contenttype=text/html
The image for each category should be displayed above its name.
Module 5: Using HTTP to Access XML Data 45
Best Practices
Avoid using URL queries except for testing
Choose an appropriate security model
Use server-side templates with parameters
Use server-side XSL processing on the Web
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Consider the following best practices when using the HTTP publishing
capabilities of SQL Server.
Avoid Using URL Queries Except for Testing
URL queries are useful for testing SQL Server virtual directories. However, in a
production environment, they allow users to submit any SQL query to the
server. Although you can use database object permissions to prevent access to
sensitive data, you should generally avoid allowing users to specify their own
queries. This is particularly true when publishing a database on the Internet.
Topic Objective
To describe best practices
for HTTP database
publishing.
Lead-in
Consider these best
practices when using the
HTTP publishing capabilities
of SQL Server.
46 Module 5: Using HTTP to Access XML Data
Choose an Appropriate Security Model
Ensure that the security model you implement will provide adequate protection
of your data while minimizing the impact on manageability and scalability. In
an intranet environment, you may want to use Windows Integrated
Authentication to allow different database access rights to different groups of
users. In an Internet solution, specifying that the virtual directory should always
log on by using a particular Windows account will create a solution that is more
scalable, because all users access the database by using the same connection
string, making connection pooling more efficient. This solution is also more
manageable, because only one Windows account must be granted access to the
database.
Generally, you should avoid using SQL Server logins, and configure the server
to accept Windows logins only.
Use Server-Side Templates with Parameters
Using server-side templates abstracts the database schema from users, ensuring
a more secure solution. You should use parameters whenever users need to
specify selection criteria, instead of allowing users to post their own templates
from the client.
Use Server-Side XSL Processing on the Web
Use the sql:xsl attribute in templates that will be accessed from the Web to
apply style sheets on the server. This allows your data to be accessed by any
browser.
Module 5: Using HTTP to Access XML Data 47
Review
Enabling HTTP Access to SQL Databases
Publishing XML Templates on the Server
Posting Query Templates from the Client
Publishing a Database Object
*****************************ILLEGAL FOR NON-TRAINER USE******************************
1. Which security model allows users on the Web to access your site
anonymously and retrieve data from the database?
The trusted server model, using either a Windows or SQL Server login.
2. What URL should be used to execute the following query as a URL query,
returning a document with a directory element named <customerdata>
from a virtual directory named data on a server called webserver?
SELECT customerid, firstname, lastname
FROM customers
WHERE lastname LIKE 'M%'
FOR XML AUTO
http://webserver/data?sql=SELECT customerid, firstname, lastname
FROM customers WHERE lastname LIKE 'M%25' FOR XML
AUTO&root=customerdata
3. A server named webserver hosts a virtual directory named data, which
contains the template virtual name HR. What URL would be used to pass
an employeeid parameter with a value of 2 to a template named
employees.xml?
http://webserver/data/HR/employees.xml?employeeid=2
Topic Objective
To reinforce module
objectives by reviewing key
points.
Lead-in
The review questions cover
some of the key concepts
taught in the module.
48 Module 5: Using HTTP to Access XML Data
4. The following template is saved as products.xml in the virtual name
catalog in the virtual directory ecommerce on the Web server
www.contoso.msft. What URL would you use to retrieve the products in
category 3 as HTML?
<?xml version="1.0"?>
<products xmlns:sql="urn:schemas-microsoft-com:xml-sql"
sql:xsl="products.xsl">
<sql:header>
<sql:param name="categoryid">1</sql:param>
</sql:header>
<sql:query>
SELECT productid, productname, price
FROM products product
WHERE categoryid = @categoryid
FOR XML AUTO
</sql:query>
</products>
http://www.contoso.msft/ecommerce/catalog/products.xml
?categoryid=3&contenttype=text/html
5. You want to allow templates to be posted from a client. What configuration
options should you set?
Allow URL Queries
Allow POST Queries
Maximum POST size
6. Assuming that you have the dbobject virtual name dbobject in the virtual
directory data on the server webserver, what URL is required to retrieve
the photo field for the record in the employees table with an
employeeid value of 1?
http://webserver/data/dbobject/employees[@employeeid='1']/@photo
Contents
Overview 1
Using Mapping Schemas 2
Using Schemas to Retrieve Data 11
Lab 6.1: Using Mapping Schemas 21
Mapping Multiple Tables 30
Lab 6.2: Mapping Multiple Tables 37
Annotating an Existing Schema 42
Lab 6.3: Annotating an Existing Schema 52
Best Practices 56
Review 57
Module 6: Using
Mapping Schemas
Information in this document is subject to change without notice. The names of companies,
products, people, characters, and/or data mentioned herein are fictitious and are in no way intended
to represent any real individual, company, product, or event, unless otherwise noted. Complying
with all applicable copyright laws is the responsibility of the user. No part of this document may
be reproduced or transmitted in any form or by any means, electronic or mechanical, for any
purpose, without the express written permission of Microsoft Corporation. If, however, your only
means of access is electronic, permission to print one copy is hereby granted.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
2001 Microsoft Corporation. All rights reserved.
Microsoft, ActiveX, BackOffice, BizTalk, MSDN, MS-DOS, SQL Server, Visual Basic, Visual
C++, Visual InterDev, Visual J++, Visual Studio, Windows, Windows Media, Windows NT, and
Windows 2000 are either registered trademarks or trademarks of Microsoft Corporation in the
U.S.A. and/or other countries.
Other product and company names mentioned herein may be the trademarks of their respective
owners.
Module 6: Using Mapping Schemas iii
Instructor Notes
This module introduces students to the use of XML-Data Reduced (XDR)
Schemas as mapping schemas, and discusses the main annotations the students
will need in order to map an Extensible Markup Language (XML) document to
data in a Microsoft SQL Server
database.
After completing this module, students will be able to:
Describe the uses and structure of annotated schemas.
Create annotated schemas that map business documents to database entities.
Use the XML Path Language (XPath) to access data through an annotated
schema.
Use Microsoft ActiveX Data Objects (ADO) to request data by using an
annotated schema.
Access data by using a schema over the Hypertext Transport Protocol
(HTTP).
Materials and Preparation
This section provides the materials and preparation tasks that you need to teach
this module.
Required Materials
To teach this module, you need the following materials:
Microsoft PowerPoint file 2091a_06.ppt
The XDR.xml example schema (for the demonstration)
Preparation Tasks
To prepare for this module, you should:
Read all of the materials for this module.
Complete the labs.
Practice the demonstration.
Presentation:
90 Minutes
Lab:
90 Minutes
iv Module 6: Using Mapping Schemas
Demonstration
This section provides demonstration procedures that will not fit in the margin
notes or are not appropriate for the student notes.
Creating an Annotated Schema
To prepare for the demonstration
1. Follow the demonstration steps to create the schema.
2. Because the schema is based on data in the Northwind Traders database,
you might want to extend the demonstration by publishing the schema in a
virtual name and accessing data through it with Microsoft Internet Explorer.
Module 6: Using Mapping Schemas v
Module Strategy
Use the following strategies to present this module:
Using Mapping Schemas
This section sets the scene and explains why schemas are a good way to
retrieve data. First, introduce schemas as a way of defining business
documents to be exchanged between trading partners or applications. Then,
describe how to create a default mapping between database entities and
XML documents by using a mapping schema. Finally, emphasize that in
most production environments, you will need to add annotations in order to
map your business documents to database entities.
Using Schemas to Retrieve Data
Explain that there are three basic ways to retrieve data with a schema: by
using ADO, by referencing the schema in an XML template, and by
publishing the schema in a virtual name. Regardless of which approach you
take, you must use an XPath expression to define the rows you want to
return.
Mapping Multiple Tables
Explain that this section presents a much more realistic use of mapping
schemas, because most business data is stored in a relational format and
normalized into multiple tables. Emphasize the importance of the sql:key-
fields annotation, which ensures that the results are grouped correctly by
identifying the primary key. Although not always required, you should
encourage students to use the sql:key-fields annotation whenever they create
a schema with a relationship annotation.
Annotating an Existing Schema
It is very likely that most mapping schemas in a business solution will be
based on existing schemas rather than newly created schemas designed
explicitly to map data. This section discusses the annotations that can be
used to include non-mapped elements (such as the root element or collection
elements) in a mapping schema. It is also worth pointing out that if the
schema contains a root element annotated with the sql:is-constant
annotation, you do not have to specify a root element when retrieving data
because a well-formed document will be returned.
Module 6: Using Mapping Schemas 1
Overview
Using Mapping Schemas
Using Schemas to Retrieve Data
Mapping Multiple Tables
Annotating an Existing Schema
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Mapping schemas are XML-Data Reduced (XDR) Schemas that specify the
structure of an Extensible Markup Language (XML) document and map the
elements and attributes it contains to tables and columns in a Microsoft
SQL Server
database.
After completing this module, you will be able to:
Describe the uses and structure of annotated schemas.
Create annotated schemas that map business documents to database
entities.
Use the XML Path Language (XPath) to access data through an annotated
schema.
Use Microsoft ActiveX Data Objects (ADO) to request data by using an
annotated schema.
Access data by using a schema over the Hypertext Transport Protocol
(HTTP).
Topic Objective
To provide an overview of
the module topics and
objectives.
Lead-in
In this module, you will learn
how to use mapping
schemas to retrieve XML
data and map business
document definitions to data
in a SQL Server database.
2 Module 6: Using Mapping Schemas
Using Mapping Schemas
Using Schemas for Data Exchange
Defining Business Documents Using Schemas
Defining a Default Table-to-Schema Mapping
Adding Annotations to a Schema
Demonstration: Creating an Annotated Schema
*****************************ILLEGAL FOR NON-TRAINER USE******************************
You can use XDR Schemas to define an XML representation of a specific
business document. This type of schema is particularly useful when multiple
organizations must exchange business documents by using XML, because an
XDR Schema provides a way to agree on a documents XML format. Later in
this module, you will see how to use schemas to access data in SQL Server
tables. For example, a retailer and a supplier could agree to use a schema to
define a purchase order document that they will exchange.
You use a mapping schema to associate a business documents representation
in XML with the underlying data in the database. You define the mapping by
using table and column names to define XML elements and attributes. You can
also use an annotated schema that contains annotations that map XML data to
tables and columns in the database. You use an annotated schema to specify
exactly which elements and attributes map to database tables and columns.
In addition, you can specify XPath queries against the XML view by using the
mapping schema to query the database. The result of this type of query is an
XML document.
This section discusses XDR Schemas and the creation of mapping schemas.
Topic Objective
To introduce the topics in
this section.
Lead-in
In this section, we will
examine how to map XDR
Schemas to SQL data.
Module 6: Using Mapping Schemas 3
Using Schemas for Data Exchange
Supplier
Purchase order
Catalog
Retailer
Catalog schema
Purchase order schema
*****************************ILLEGAL FOR NON-TRAINER USE******************************
When two organizations need to agree on the XML representation of a
particular type of business document, they can define a schema.
Defining Business Documents with Schemas
Schemas are XML documents that define the elements and attributes that can be
legally used in a particular class of XML document. Schemas are useful when
two business partners need to agree on a common definition for a document
they will exchange.
For example, a retailer and a supplier might create a schema that defines a
purchase order. Because there is an agreed definition of what a purchase order
should look like, the two organizations can implement business processing
logic to handle the purchase order documents that they will exchange.
Similarly, a second schema could be used to define a catalog document,
allowing catalog data to be exchanged in a consistent format.
Mapping Data in Tables to XML with Schemas
You can use XML schemas with SQL Server 2000 to map the data in XML
business documents to data in the tables of a SQL Server database. This
provides a way of generating XML business documents that contain data from
SQL Server.
Topic Objective
To explain why schemas are
useful for exchanging data.
Lead-in
Schemas are useful when
two organizations need to
agree on the XML
representation of a business
document.
Delivery Tip
This slide builds
automatically. First, the slide
shows a purchase order
schema being used as an
agreed definition for XML
purchase orders that a
retailer will send to a
supplier. Then, it shows a
catalog schema being used
as an agreed definition for a
catalog document that will
be downloaded from the
supplier.
You can restart the build by
pressing the LEFT ARROW
key on the keyboard.
4 Module 6: Using Mapping Schemas
Defining Business Documents Using Schemas
Agree on an XML representation of the document
Create an XML-Data Reduced (XDR) schema
Reference namespaces for element, attribute, and data
types
Define valid elements and attributes
*****************************ILLEGAL FOR NON-TRAINER USE******************************
You can use schemas to define an XML documents structure. The ability to
define a valid XML representation of a business document is particularly
important when instances of the document must be exchanged between systems
and organizations.
Agreeing on an XML Representation of the Document
When two organizations or applications must exchange a business document
such as a purchase order or invoice, they must agree on a common definition of
a valid instance of that document. Consider the following issues when agreeing
on the definition of an XML representation of a business document:
Which elements and attributes can be included in the document?
Which elements or attributes are mandatory, and which are optional?
How many instances of each element in the document are allowed?
What data types must the values in the elements and attributes be?
You can define the agreement in an XDR Schema, which is an XML document
that contains the definition for a particular type of business document.
Creating an XDR Schema
XDR Schemas commonly use two namespaces, as described in the following
table.
Namespace Description
urn:schemas-microsoft-com:xml-data Defines XDR elements and attributes.
urn:schemas-microsoft-com:datatypes Defines data types for elements and
attributes.
Topic Objective
To describe how to use an
XDR Schema to define the
XML representation of a
business document.
Lead-in
XDR provides a way to
define the structure of an
XML document: its elements
and attributes and their
types.
Delivery Tip
It is assumed that the
students are already familiar
with XDR syntax. Therefore,
the XDR elements are not
explained in detail at this
time.
Module 6: Using Mapping Schemas 5
The xml-data namespace is necessary to define the elements and attributes
within the XDR Schema. Use the optional datatypes namespace to define types
of the elements and attributes.
Consider the following important elements in an XDR Schema.
Element Description
<Schema> Defines the root element for an XDR
Schema.
<ElementType> Defines a type of element that can be
placed in a document.
<element> Defines an instance of an element.
<AttributeType> Defines a type of attribute that can be
placed within an element.
<attribute> Defines an instance of the attribute.
For example, consider an XML document that represents a purchase order with
an <Order> element that contains multiple <Item> elements. Each purchase
order has OrderID and CustomerID attributes. Each item within the purchase
order contains a ProductID and a Quantity attribute.
The following example shows an XDR Schema that defines a purchase order
document.
<?xml version="1.0" ?>
<Schema xmlns="urn:schemas-microsoft-com:xml-data">
<ElementType name="Item">
<AttributeType name="ProductID"/>
<AttributeType name="Quantity"/>
</ElementType>
<ElementType name="Order">
<AttributeType name="OrderID"/>
<AttributeType name="CustomerID"/>
<attribute type="OrderID"/>
<attribute type="CustomerID"/>
<element type="Item"/>
</ElementType>
</Schema>
You can find a reference for XDR Schemas at
http://msdn.microsoft.com/xml/reference/schema/start.asp
Delivery Tip
You might want to draw
attention to the precise
capitalization of these XDR
elements.
Example
Tip
6 Module 6: Using Mapping Schemas
Defining a Default Table-to-Schema Mapping
Creating an Attribute-Centric Mapping
Elements map to tables or views
Attributes map to columns
Creating an Element-Centric Mapping
Use textOnly to map columns to child elements
*****************************ILLEGAL FOR NON-TRAINER USE******************************
You can use an XDR Schema to map XML data to data in a SQL Server
database. The SQL Server OLEDB (SQLOLEDB) Provider recognizes a
default mapping between a schema and a single table when the element and
attribute names in the schema precisely match table and column names in the
database. This correspondence allows data to be returned to a client application
by using the mapping schema.
Creating an Attribute-Centric Mapping
In an XDR Schema, an XML element by default maps to the table or view of
the same name, and an XML attribute maps to the column of the same name
within that table or view. This kind of mapping is convenient when there is a
single underlying database table and you require attribute-centric documents.
In the following example, the annotated schema contains an <ElementType>
element with a name attribute of Orders, and therefore is associated with the
Orders table. The OrderID and OrderDate attributes defined within the
<Orders> element are associated with corresponding columns of the Orders
table in the database.
<?xml version="1.0"?>
<Schema xmlns="urn:schemas-microsoft-com:xml-data">
<ElementType name="Orders">
<AttributeType name="OrderID"/>
<AttributeType name="OrderDate"/>
<attribute type="OrderID"/>
<attribute type="OrderDate"/>
</ElementType>
</Schema>
Topic Objective
To explain the default
mappings between the
database and XML
elements in the schema.
Lead-in
XDR Schemas can be
mapped to data in a SQL
Server database. The
SQLOLEDB Provider
recognizes a default
mapping between a schema
and a single table.
Key Points
The SQLOLEDB provider
identifies the mapping
between the schema and
the database table. XDR
provides no database
mapping functionality of its
own.
Example
Module 6: Using Mapping Schemas 7
The results of a query against the Northwind Traders database that uses this
schema appear as a set of <Orders> elements. Each element has OrderID and
OrderDate attributes as follows:
<Orders OrderID="10248" OrderDate="1996-07-04T00:00:00" />
<Orders OrderID="10249" OrderDate="1996-07-05T00:00:00" />
<Orders OrderID="10250" OrderDate="1996-07-08T00:00:00" />
Creating an Element-Centric Mapping
The default mapping produces attribute-centric output. If you require element-
centric output, the schema must contain an ElementType declaration with a
textOnly value for its content attribute. This maps database columns to
elements instead of attributes.
The following example shows a mapping schema that uses element-centric
mapping with the Orders table from the Northwind Traders database.
<?xml version="1.0"?>
<Schema xmlns="urn:schemas-microsoft-com:xml-data">
<ElementType name="OrderID" content="textOnly"/>
<ElementType name="OrderDate" content="textOnly"/>
<ElementType name="Orders">
<element type="OrderID"/>
<element type="OrderDate"/>
</ElementType>
</Schema>
Running results from this schema against the Northwind database produces an
XML fragment with the following format:
<Orders>
<OrderID>10248</OrderID>
<OrderDate>1996-07-04T00:00:00</OrderDate>
</Orders>
<Orders>
<OrderID>10249</OrderID>
<OrderDate>1996-07-05T00:00:00</OrderDate>
</Orders>
<Orders>
<OrderID>10250</OrderID>
<OrderDate>1996-07-08T00:00:00</OrderDate>
</Orders>
Element and attribute names in XML are always case-sensitive.
Names of tables and columns in SQL Server may be case-sensitive, depending
on the configuration of the database. To avoid problems, annotate the database
as if the database names were case-sensitive.
Example
Caution
8 Module 6: Using Mapping Schemas
Adding Annotations to a Schema
Reference the XML-SQL namespace
Use the sql:relation annotation to create an alias for a
table or view
Use the sql:field annotation to create an alias for a
column
<?xml version="1.0"?>
<Schema
xmlns="urn:schemas-microsoft-com:xml-data"
xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<ElementType name="Invoice" sql:relation="Orders">
<AttributeType name="InvoiceID"/>
<attribute type="InvoiceID" sql:field="OrderID"/>
</ElementType>
</Schema>
<?xml version="1.0"?>
<Schema
xmlns="urn:schemas-microsoft-com:xml-data"
xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<ElementType name="Invoice" sql:relation="Orders">
<AttributeType name="InvoiceID"/>
<attribute type="InvoiceID" sql:field="OrderID"/>
</ElementType>
</Schema>
*****************************ILLEGAL FOR NON-TRAINER USE******************************
The default mapping is convenient in simple cases, but assumes that element
and attribute names in the XML output correspond exactly to table and column
names in the underlying database.
It is more common to annotate an existing schema than to create a new schema.
You will often have an existing schema and database where the names of
elements and attributes do not match the names in the database tables and
columns. In this case, you should use a mapping schema that contains
annotations.
Referencing the XML-SQL Namespace
To add annotations to a schema, you must reference the schemas XML-SQL
namespace. The XML-SQL namespace defines the annotations that can be
added to a schema in order to map XML data to SQL Server data.
The following table shows the annotations that you can add to a schema.
Annotation Purpose
relation Map an element to a table.
field Map an element or attribute to a column.
relationship Define a primary/foreign key relationship.
datatype Define the SQL data type of a column.
key-fields Define the primary key field(s) for a table.
is-constant Specify an element or attribute that appears in the XML
document but does not map to a column.
map-field Use to omit non-mapped schema elements or attributes from the
resulting XML document.
limit-field
& field-value
Use to filter the results based on a field value in a related table.
Topic Objective
To show how to create an
alias for table names and
column names by adding
annotations to an existing
schema.
Lead-in
When a schemas elements
and attributes do not have
the same names as tables
and columns, you can use
annotations to map the data.
Delivery Tip
Explain that most of these
annotations will be
discussed in more detail
later in the module.
Module 6: Using Mapping Schemas 9
(continued)
Annotation Purpose
target-namespace Use to reference an alternative XML namespace (can be used to
validate resulting documents against the schema). Note that this
annotation can only be used when a schema is referenced in a
template. For more information, see SQL Server Books Online.
id-prefix Prepend XML ID, IDREF, or IDREFS fields with a unique
identifier.
use-cdata Generate XML data in a CDATA structure.
url-encode Encode binary large objects (BLOB) data as a URL reference.
overflow-field Define a column that contains overflow data.
Using the sql:relation Annotation to Map a Table
Use the sql:relation annotation to map an XML node in the XDR Schema to a
database table or view in the following circumstances:
When an XML element represents a table
When an XML element or attribute represents a column in a different table
from the parent element
Using the sql:field Annotation to Map a Column
You can add the sql:field annotation to map an XML node in the XDR Schema
to a database column.
In the following example, the annotated schema defines an XML document
containing a set of <Item> elements, each having InvoiceID, ProductID, and
Qty attributes. The <Item> element is mapped to the [Order Details] table by
using the sql:relation annotation. The InvoiceID, ProductID, and Qty
attributes are mapped to the OrderID, ProductID, and Quantity columns,
respectively, by using the sql:field annotation.
<?xml version="1.0"?>
<Schema
xmlns="urn:schemas-microsoft-com:xml-data"
xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<ElementType name="Item" sql:relation="[Order Details]">
<AttributeType name="InvoiceID"/>
<AttributeType name="ProductID"/>
<AttributeType name="Qty"/>
<attribute type="InvoiceID" sql:field="OrderID"/>
<attribute type="ProductID" sql:field="ProductID"/>
<attribute type="Qty" sql:field="Quantity"/>
</ElementType>
</Schema>
The following example shows the output from the preceding schema:
<Item InvoiceID="10278" ProductID="44" Qty="16" />
<Item InvoiceID="10278" ProductID="59" Qty="15" />
<Item InvoiceID="10278" ProductID="63" Qty="8" />
<Item InvoiceID="10278" ProductID="73" Qty="25" />
Example
10 Module 6: Using Mapping Schemas
Demonstration: Creating an Annotated Schema
*****************************ILLEGAL FOR NON-TRAINER USE******************************
In this demonstration, you will see how to create a simple annotated schema.
Topic Objective
To demonstrate how to
create a simple annotated
schema.
Lead-in
In this demonstration, you
will see how to create a
simple annotated schema.
Delivery Tip
1. Open the file <install
folder>\DemoCode\Mod06\
Annotated\XDR.xml with
Notepad.
2. Add the annotation
xmlns:sql="urn:schemas-
microsoft-com:xml-sql" to
the Schema attribute.
3. Add the annotation
sql:relation="Products" to
the ElementType element.
4. Add the annotation
sql:field="ProductID" to the
first attribute element.
5. Add the annotation
sql:field="ProductName" to
the second attribute.
Alternatively, you may edit
the file <install
folder>\DemoCode\Mod06\
Annotated\Schema.xml to
show the complete schema.
Module 6: Using Mapping Schemas 11
Using Schemas to Retrieve Data
Specifying Data with an XPath Expression
Using a Schema with an ADO Command Object
Querying a Schema from a Template
Publishing a Schema Virtual Name
Controlling Schema Caching
*****************************ILLEGAL FOR NON-TRAINER USE******************************
You can develop client applications that use mapping schemas to retrieve XML
data from a SQL Server database. An XPath expression determines the data that
is retrieved.
You can reference mapping schemas by ADO 2.6based applications, and by
XML templates. You can also publish mapping schemas in a virtual name and
access them directly by using a Uniform Resource Locator (URL).
This section discusses how to create client applications that use mapping
schemas.
Topic Objective
To introduce the topics in
this section.
Lead-in
In this section, we will
examine how client
applications can retrieve
XML data by using a
schema.
12 Module 6: Using Mapping Schemas
Specifying Data with an XPath Expression
XPath query selects the elements to generate
Start element
Selection criteria
SQLOLEDB Provider supports a subset of Xpath
Filtering the Result
/Item
/Item
/Item[@InvoiceID='10278']
/Item[@InvoiceID='10278']
*****************************ILLEGAL FOR NON-TRAINER USE******************************
By itself, an annotated schema describes the structure of an XML document and
how it relates to the underlying database. To perform a query, you need a way
to specify which elements will be generated, as well as any selection criteria.
An XPath query performs this role.
Using an XPath to Query an Annotated Schema
You can specify XPath expressions in several ways, such as by using a URL, a
template, or programmatically through ADO. These techniques will be
discussed later in this module. This section illustrates the syntax and semantics
of XPath queries.
Topic Objective
To show how XPath
expressions are used to
specify the data returned
from a schema.
Lead-in
To generate an XML
document, an XPath
expression must be supplied
with the schema and
database.
Delivery Tip
The fundamentals of XPath
queries were discussed in
Module 1, Using XML and
Microsoft SQL Server 2000.
For more information, refer
to Course 1913, Exchanging
and Transforming Data
Using XML and XSLT,
Module 2, Selecting and
Navigating Nodes Using
XPath.
Module 6: Using Mapping Schemas 13
For example, assume that you have the following annotated schema, which
describes invoice item information from the Northwind Traders database.
<?xml version="1.0"?>
<Schema
xmlns="urn:schemas-microsoft-com:xml-data"
xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<ElementType name="Item" sql:relation="[Order Details]">
<AttributeType name="InvoiceID"/>
<AttributeType name="ProductID"/>
<AttributeType name="Qty"/>
<attribute type="InvoiceID" sql:field="OrderID"/>
<attribute type="ProductID" sql:field="ProductID"/>
<attribute type="Qty" sql:field="Quantity"/>
</ElementType>
</Schema>
To select all <Item> elements, you can use the following XPath expression:
/Item
Filtering the Result
You can use the element selection features of XPath expressions to filter
results. For example, to select only items belonging to invoice 10278, use the
following XPath expression:
/Item[@InvoiceID='10278']
Note that in the preceding examples, where sql:relation and sql:field
annotations have been added to create an alias for the table and column names
of the database, the aliased names are used in the XPath expression.
The SQLOLEDB Provider implements a subset of the XPath
specification. The full XPath specification is at http://www.w3.org/TR/xpath ;
See the
SQL Server 2000 documentation for details of the supported subset.
Example
Delivery Tip
Point out that the @ symbol
denotes an attribute name
here.
Caution
14 Module 6: Using Mapping Schemas
Using a Schema with an ADO Command Object
Specifying the Schema
Properties("Mapping Schema" )
May be relative to Properties("Base Path" )
Specifying the XPath Expression
Dialect = "{ec2a4293-e898-11d2-b1b7-00c04f680c56} "
CommandText = XPath
Specifying the Root Element
Properties("XML Root" )
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Version 2.6 of the ADO libraries (supplied with SQL Server 2000) supports
access to XML data through annotated schemas. You use the ADO Command
object to reference the schema, and to specify the XPath expression to be used.
The resulting XML document is written to the ADO Stream object assigned to
the Command objects Output Stream property.
Specifying the Schema
You assign the file name of the schema to the Mapping Schema provider-
specific property in the Properties collection of the command. You can specify
the absolute path to the schema file, or set the Base Path property and use a
relative path. The following code sets the Base Path and Mapping Schema
properties of a Command object named objCmd:
objCmd.Properties("Base Path") = "c:\Schemas"
objCmd.Properties("Mapping Schema") = "InvoiceSchema.xml"
Specifying the XPath Expression
By default, The SQLOLEDB Provider works with Command objects that use
SQL as the query language. To use XPath as the query language, you must set
the Dialect property of the Command object to DBGUID_XPATH GUID
"{ec2a4293-e898-11d2-b1b7-00c04f680c56}", which represents the XPath
dialect. If you omit this step, the query string will be interpreted as SQL rather
than as an XPath query, resulting in an error.
Assign the XPath query to the CommandText property of the Command
object. The following code sets the Dialect and CommandText properties:
objCmd.Dialect = "{ec2a4293-e898-11d2-b1b7-00c04f680c56}"
objCmd.CommandText = "Invoice[@InvoiceNo='1923']
Topic Objective
To show how to use an
ADO Command object for a
schema-based query.
Lead-in
You can use an ADO
Command object to retrieve
XML data through a
schema.
For Your Information
In the Active Server Pages
(ASP) environment, the
Response object may also
be used as an output
stream.
Module 6: Using Mapping Schemas 15
Specifying the Root Element
To specify the name of a root element for the generated XML, set the XML
Root member of the Command objects Properties collection.
The XML Root property is optional. If it is supplied, a complete XML
document will be generated with a root element and <?xml ?> processing
instruction. If the root element is omitted, an XML fragment will be returned.
The following code sets the xml root property:
ObjCmd.Properties("xml root") = "Invoice"
The following example shows how to use an ADO Command object to retrieve
XML data by specifying a schema, an XPath expression, and a root element.
Dim objConnect
Dim objCmd
Dim objStrm
Dim strXMLResults
Set objConnect=CreateObject("ADODB.Connection")
objConnect.Open "Provider=SQLOLEDB;Data Source=DBServer;
Initial catalog=Northwind;Integrated Security=SSPI;"
Set objStrm=CreateObject("ADODB.Stream")
objStrm.Open
Set objCmd=CreateObject("ADODB.Command")
With objCmd
Set .ActiveConnection = objConnect
.Properties("output stream")=objStrm
.Properties("mapping schema")="c:\schemas\invoiceschema.xml"
.Properties("xml root")="Invoice"
.Dialect="{ec2a4293-e898-11d2-b1b7-00c04f680c56}"
.CommandText="Invoice[@InvoiceNo='1923']
.Execute, , 1024 ' value for adExecuteStream
End With
StrXMLResults=objStrm.ReadText
By default, an XML document is created with UTF-8 encoding, which
represents accented and non-Latin characters by using multibyte escape
sequences. If your character data falls entirely within the 7-bit character set, this
will not cause any problems. Otherwise, ensure that your other XML-
processing tools can correctly handle UTF-8 escape sequences. You can specify
alternative encodings by setting the Properties("Output Encoding") property.
You can apply an XSL style sheet before sending the XML results to the
output stream. To specify which style sheet to use, set the Properties("xsl")
property.
Example
Delivery Tip
This caution is necessary for
the lab work, because
Microsoft Internet Explorer
version 5.5 has difficulty
rendering XML documents
containing UTF-8 escape
sequences. The lab uses
ISO-8859-1 (Latin 1)
encoding.
Caution
Tip
16 Module 6: Using Mapping Schemas
Querying a Schema from a Template
Using an <xpath-query> Element in a Template
mapping-schema attribute defines the schema
Element contains the XPath expression
Passing Parameters to a Template
The param annotation defines parameter and default
Use $ as parameter placeholder
*****************************ILLEGAL FOR NON-TRAINER USE******************************
XML template files can contain queries and can be published in a SQL Server
virtual directory application. Although template files usually contain a SQL
query, a template file alternatively can contain an XPath expression and a
reference to an annotated schema.
Using an <xpath-query> Element in a Template
To reference a mapping schema, place an <xpath-query> element within the
root element. This element must contain a mapping-schema attribute that
identifies the annotated schema to be used. The text within the element is the
XPath for the query.
The xml-sql namespace must appear in the template, usually by specifying the
namespace urn:schemas-microsoft-com:xml-sql, with an alias of sql, in the root
element of the template.
The following is an example of a template that contains the XPath expression
/Invoice and a reference to the annotated schema orderschema.xml.
<?xml version="1.0" ?>
<purchaseorder xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<sql:xpath-query mapping-schema="orderschema.xml">
/Invoice
</sql:xpath-query>
</purchaseorder>
Topic Objective
To show how an annotated
schema can be used from a
template.
Lead-in
A template file can contain
an annotated schema.
Example
Module 6: Using Mapping Schemas 17
You can then publish the template in a template virtual name, and execute
queries by using a URL. For example, you could create a template called
order.xml and save it in the virtual name templates. If you publish this virtual
name in the virtual directory "retaildata" on the webserver server, you can
access the template by using the following URL:
http://webserver/retaildata/templates/order.xml
Passing Parameters to a Template
You can declare parameters in a template file by using the <param> element
inside the header element. Each parameter has a name and a default value that is
used if parameters are not supplied. In the XPath query, the dollar sign ($)
signifies that a parameter value will be used.
In the following example, the template has an OrderID parameter with the
default value 0. The XPath query selects the <publishers> elements with a state
value equal to the parameter value.
<?xml version="1.0" ?>
<root xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<sql:header>
<sql:param name='OrderID'>0</sql:param>
</sql:header>
<sql:xpath-query mapping-schema="orderschema.xml">
/orderdetails[@orderid=$OrderID]
</sql:xpath-query>
</root>
When you invoke this template from a browser, you can provide a value for
OrderID as an HTTP query string in the URL, as follows:
http://webserver/retaildata/templates/order.xml?OrderID=1907
Delivery Tip
Compare this process to the
process of creating SQL-
based templates, which was
covered in Module 5, Using
HTTP to Access XML Data.
Delivery Tip
The parameter-passing
mechanism is similar to
SQL-based templates,
described in Module 5,
Using HTTP to Access
XML Data. However, when
a schema is used, the @
and $ characters perform
different roles.
Example
18 Module 6: Using Mapping Schemas
Publishing a Schema Virtual Name
Folders containing schemas are configured as virtual
names
Client applications access the schema by using a URL
C:\SQLSite (Virtual root data)
C:\Schemas (Virtual name schemas)
inv.xml
Webserver
http://webserver/query/schemas/inv.xml/Item?root=Invoice
http://webserver/query/schemas/inv.xml/Item?root=Invoice
*****************************ILLEGAL FOR NON-TRAINER USE******************************
You can save schema files in any folder on the Web server. The schema files do
not need to be in the same directory tree as the virtual root. Folders that contain
schema files are configured as virtual names to allow them to be accessed in a
URL.
Configuring a Schema Virtual Name
You can configure virtual names by using the Microsoft Management Console
tool Configure SQL XML Support in IIS (where IIS represents Microsoft
Internet Information Services). Consider the following issues when creating a
virtual name for a schema:
The virtual name must be unique within the virtual root application.
The virtual name must be specified with the type Schema.
The virtual name must relate to a physical folder containing XML schema
files.
A virtual name can contain a hierarchy of subfolders if desired.
Appropriate file system permissions must be assigned to the physical folder
referenced by the virtual name, and to its subfolders and files. The accounts
that require access depend on the security model for the virtual root.
Topic Objective
To describe how to create
and use virtual names for
schemas.
Lead-in
You save schema files in a
folder that is configured as a
virtual name.
Delivery Tip
This process is the same as
configuring a schema virtual
name, but with schemas
substituted for templates.
Module 6: Using Mapping Schemas 19
Accessing the Schema by Using a URL
You can access an annotated schema over HTTP by specifying the schema
name, the XPath, and the root element in a URL.
To retrieve data from a Schema virtual name, create a URL that includes the
following information:
The path to the server, virtual root, and virtual name.
The name of the schema file.
An XPath expression defining the data to be returned.
A root parameter to specify the root element name. (If you omit this, you
will retrieve an XML fragment with no root element.)
The following example retrieves an XML document from the webserver server
through the virtual root query, which has the virtual name schemas for
schemas. The schema file name is inv.xml, the XPath expression is Item, and
the name of the root element is Invoice.
http://webserver/query/schemas/inv.xml/Item?root=Invoice
Example
20 Module 6: Using Mapping Schemas
Controlling Schema Caching
Disabling Caching for the Development Environment
Set disable schema caching option for HTTP
Use SS STREAM FLAGS property for ADO
*****************************ILLEGAL FOR NON-TRAINER USE******************************
By default, IIS maintains an in-memory cache of the XML files that define the
annotated schemas. When you execute an XPath query against an annotated
XDR Schema, the schema is stored in memory, and the necessary data
structures are built in memory. If you have set schema caching, the schema
remains in memory, thus improving performance for subsequent XPath queries.
This method of caching is intended to promote efficiency by reducing the
number of times a file system is accessed. However, if the schema files are
changing (especially in a development environment where changes may be
made very frequently), the caching will cause the server to use only old
versions of the schema instead of later ones.
Disabling Caching for the Development Environment
You should not cache the schemas during development because changes to the
schemas are not reflected in the cache for about two minutes. When you disable
caching, a schema reloads each time a query is executed against it.
To disable caching for a virtual root, edit the properties of the virtual directory
by using the Configure SQL XML Support in IIS tool. In the Properties dialog
box, click the Advanced tab for the virtual directory, and then select Disable
Caching of Mapping Schemas.
To disable caching when using ADO, set the SS STREAM FLAGS property to
STREAM_FLAGS_DONTCACHESMAPPINGCHEMA (8) as shown in
the following example:
objCmd.Properties("SS STREAM FLAGS") = 8
Topic Objective
To describe the schema-
caching mechanism and
discuss when it is
appropriate to use it.
Lead-in
IIS will cache schema
documents in memory by
default. You may want to
change this in a
development environment.
Module 6: Using Mapping Schemas 21
Lab 6.1: Using Mapping Schemas
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Objectives
In this lab, you will create a simple mapping schema and generate XML
documents from the schema in different ways.
After completing this lab, you will be able to:
Create annotated schemas that map business documents to single database
tables.
Use XPath language to access data through a mapping schema.
Use ADO 2.6 to request data by using a mapping schema.
Access data by referencing a mapping schema in a template.
Access data by accessing a schema published in a schema virtual name.
Prerequisites
Before working on this lab, you must understand:
XDR Schema syntax.
XML-SQL annotations for single tables.
ADO development by using Microsoft Visual Basic Scripting Edition.
Lab Setup
To complete this lab, you need a computer running Microsoft Windows 2000
Server, with SQL Server 2000 and Microsoft Internet Explorer 5.5 or later
installed.
Topic Objective
To introduce the lab.
Lead-in
In this lab, you will create a
simple mapping schema
and generate XML
documents from it in various
ways.
Explain the lab objectives.
22 Module 6: Using Mapping Schemas
Scenario
Northwind Traders has agreed to supply a copy of its product catalog to a
business partner in the form of an XML document. The root element of this
document is <Catalog>, which contains a set of <Product> elements. Each
<Product> element has the following attributes.
Attribute Description
ID Unique ID
Name Name of the product
QuantityPerUnit Number of items in each ordered unit
UnitPrice Price of each unit
InStock Number in stock
OnOrder Number on order
Discontinued 0 if available to purchase, 1 if not
The following is a sample catalog document:
<Catalog>
<Product
ID="1" Name="Chai"
QuantityPerUnit="10 boxes x 20 bags"
UnitPrice="18" InStock="39" OnOrder="0"
Discontinued="0" />
<Product
ID="2" Name="Chang"
QuantityPerUnit="24 - 12 oz bottles"
UnitPrice="19" InStock="17" OnOrder="40"
Discontinued="0" />
</Catalog>
In this lab, you will annotate an existing schema for this document and generate
XML documents from the schema in various ways.
Estimated time to complete this lab: 30 minutes
Module 6: Using Mapping Schemas 23
Exercise 1
Creating a Simple Mapping Schema
In this exercise, you will add annotations to an existing XDR Schema in order
to create a simple mapping schema. You will use a previously written test
framework that will generate an XML document from the mapping schema.
Scenario
Two business partners have agreed to use an XDR Schema for a product
catalog. You must annotate this schema to make it suitable for generating XML
documents.
To add annotations to the schema
The file ProductSchema1.xml in the folder <install folder>\
Labs\Lab06\Solution contains a solution to this procedure.
1. Open the file ProductSchema1.xml with Microsoft Notepad from the
directory <install directory>\Labs\Lab06\Starter.
2. Add the xml-sql namespace to the <Schema> element by adding the
attribute xmlns:sql="urn:schemas-microsoft-com:xml-sql".
3. Add the sql:relation annotation to the <ElementType> element that defines
the <Product> element. This element must be mapped to the Products
database table.
4. For each of the attributes defined in the schema for the <Product> element,
create the following database column mappings by using the sql:field
annotation.
Attribute Database column
ID ProductID
Name ProductName
QuantityPerUnit QuantityPerUnit
UnitPrice UnitPrice
InStock UnitsInStock
OnOrder UnitsOnOrder
Discontinued Discontinued
5. Save ProductSchema1.xml and close Notepad.
24 Module 6: Using Mapping Schemas
To test the annotated schema
1. In Windows Explorer, double-click the file TestSchema1.htm in the folder
<install directory>\Labs\Lab06\Starter. This is an application that will
generate an XML document from the schema ProductSchema1.xml and the
Northwind Traders database.
2. Click Generate.
Depending on the Internet Explorer security settings, you might see
the message An ActiveX control on this page might be unsafe to interact
with other parts of the page. Do you want to allow this interaction? If this
question appears, click Yes.
3. If the document is successfully generated, the XML document source
appears in the text area at the bottom of the screen. (You may paste the
generated document into a new file and load it into Internet Explorer to view
the results more clearly).
Note
Module 6: Using Mapping Schemas 25
Exercise 2
Using ADO to Create XML Documents
In this exercise, you will write an application that uses ADO to create an XML
document from a given mapping schema, database, and XPath expression.
Scenario
The business partners have agreed on an XDR Schema, which they have
annotated. One of the partners requires an application that generates the product
catalog document on demand.
This application should generate an XML document from the schema file
ProductSchema1.xml. Save the generated document to disk with the file name
ProductCatalog.xml.
You can find a template for this application in the file GenerateCatalog.vbs in
the directory <install directory>\Labs\Lab06\Starter. This template contains
some initialization code, and the necessary logic for the final save-to-disk
operation. You must complete the ADO part of the application.
To write the ADO application
The file GenerateCatalog.vbs in the folder <install folder>\Labs\Lab06\Solution
contains a solution to this procedure.
1. Open GenerateCatalog.vbs with Notepad from the directory
<install directory>\Labs\Lab06\Starter. Note the declarations that have
been included.
2. Find the comment ' SETUP ADO COMMAND. The ADO Command
object has been created, but is not yet initialized. After this comment you
will find a With .. End With block in which you must set up the ADO
command object objCmd by following the remaining steps.
3. Set the ActiveConnection property of objCmd to objConn.
4. Set the Dialect property of objCmd to MSSQL_GUID_XPATH. This is
the constant for the globally unique identifier (GUID) that represents the
XPath dialect.
5. Set the Mapping Schema entry in the Properties collection of objCmd to
the value in the constant sSchema, which holds the filename of the schema
file.
6. Set the XML Root entry to the value in the constant sRoot, which holds the
root element name.
7. Set the Output Stream entry to the objStream variable, which holds the
output stream.
8. Set the Output Encoding entry to ISO-8859-1. This is required because the
database contains a number of accented characters, and Internet Explorer
cannot handle this data in the default UTF-8 character encoding.
26 Module 6: Using Mapping Schemas
9. Set the CommandText property to the string in variable sXPath, which
contains the XPath expression entered by the user. The complete code block
for initialization of objCmd should resemble the following:
With objCmd
Set .ActiveConnection = objConn
.Dialect = MSSQL_GUID_XPATH
.Properties("Mapping Schema") = sSchema
.Properties("XML Root") = sRoot
.Properties("Output Stream") = objStream
.Properties("Output Encoding") = "ISO-8859-1"
.CommandText = sXPath
End With
10. Locate the comment that begins with EXECUTE COMMAND. After this
comment, write code that executes the command that sends the results to the
output stream (remembering to specify the adExecuteStream option). The
complete code block for execution of the command should read as follows:
objCmd.Execute ,, adExecuteStream
11. Save the file and close Notepad.
To Test the ADO application
1. Double-click the script file GenerateCatalog.vbs to run it.
2. The resulting XML is generated and saved to the file ProductCatalog.xml.
Double-click this file to open it with Internet Explorer and check the results.
Module 6: Using Mapping Schemas 27
Exercise 3
Using a Schema with a Template
In this exercise, you will create a template that retrieves data from an annotated
schema. You will install the template and schema files in Microsoft Internet
Information Services (IIS), configure IIS, and generate an XML document.
Scenario
A business partner wants to access the Northwind Traders catalog over HTTP.
To accomplish this, you will install an annotated schema and a template on a
Web server running IIS.
You will need an annotated schema to complete this exercise. Use the file
ProductSchema1.xml that you created in Exercise 1, or copy the solution file
from the directory <install directory>\Labs\Lab06\Solution into the directory
<install directory>\Labs\Lab06\Starter.
To create a template virtual name
Double-click the scripting host file CreateRoot.vbs from the directory
<install directory>\Labs\Labs06 directory to execute it. This script creates a
virtual root called Lab06 that allows queries based on templates and
schemas, and provides two virtual names called templates and schemas
for these purposes.
28 Module 6: Using Mapping Schemas
To create a template
The file ProductTemplate1.xml in the folder <install folder>\
Labs\Lab06\Solution contains a solution to this procedure.
1. Open Notepad to create a new XML query template.
2. Include the <?xml version="1.0"?> processing instruction at the head of the
file.
3. Create a <Catalog> element by using the urn:schemas-microsoft-
com:xml-sql namespace, aliased to the identifier sql.
4. In the <Catalog> element, place a <sql:xpath-query> element with a
mapping-schema attribute set to the name of the schema file,
ProductSchema1.xml.
5. In the <sql:xpath-query> element, place text containing the required XPath
expression (/Product). The template file should look like the following:
<?xml version="1.0"?>
<Catalog xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<sql:xpath-query mapping-schema="ProductSchema1.xml">
/Product
</sql:xpath-query>
</Catalog>
6. Save your work as ProductTemplate1.xml in the directory <install
directory>\Labs\Lab06\Starter.
To test the template
Open the following URL with Internet Explorer:
http://localhost/Lab06/templates/ProductTemplate1.xml
Internet Explorer displays the XML document representing the product
catalog.
Module 6: Using Mapping Schemas 29
Exercise 4
Using a Schema with a Virtual Name
In this exercise, you will configure IIS to allow queries to be made with an
XPath expression and an annotated schema.
Scenario
An internal division of Northwind Traders wants the ability to request the
companys product catalog. The division wants to use IIS and HTTP to execute
arbitrary XPath expressions against the schema.
You will need an annotated schema to complete this exercise. Use the file
ProductSchema1.xml that you created in Exercise 1, or copy the solution file
from the directory <install directory>\Labs\Lab06\Solution into the directory
<install directory>\Labs\Lab06\Starter.
To Enable XPath queries
1. If you completed Exercise 3, the virtual root Lab06 already exists. If you did
not complete Exercise 3, run the scripting host file CreateRoot.vbs in the
<install folder>\Labs\Lab06 folder to create the virtual root.
2. Start the Configure SQL XML Support in IIS tool from the Microsoft
SQL Server program group and expand your server.
3. View the properties of the Lab06 virtual root, and then click the Settings
tab.
4. Select the Allow XPath checkbox, click OK, and then close the IIS Virtual
Directory Management window.
To test the schema
1. Open the following URL with Internet Explorer. The Web server will return
the XML document representing the product catalog.
http://localhost/Lab06/schemas/ProductSchema1.xml
/Product?root=Catalog
The XPath expression component of the URL (/Product) is case-
sensitive, so type it exactly as shown. The other components of the URL are
not case-sensitive.
2. Modify the URL so that the XPath returns only rows where the
Discontinued field has a value of 1. The URL used should resemble the
following:
http://localhost/Lab06/schemas/ProductSchema1.xml
/Product[@Discontinued=1]?root=Catalog
Caution
30 Module 6: Using Mapping Schemas
Mapping Multiple Tables
Mapping Related Tables
Controlling XML Document Nesting
Filtering Data
*****************************ILLEGAL FOR NON-TRAINER USE******************************
In most production solutions, you store the data required for a business
document in more than one table. You use annotated schemas to map XML
elements and attributes to multiple underlying tables, and to produce nested
documents based on primary key and foreign key relationships in the database.
This section describes the annotations that you can use to reference multiple
tables.
Topic Objective
To introduce the topics in
this section.
Lead-in
In this section, we will
discuss how to map
schemas to multiple
database tables.
Module 6: Using Mapping Schemas 31
Mapping Related Tables
The sql:relationship annotation joins two database
tables
<ElementType name="Item">
</ElementType>
<ElementType name="Invoice">
<element type="Item">
<sql:relationship
key-relation="Orders"
key="OrderID"
foreign-relation="[Order Details]"
foreign-key="OrderID"/>
</element>
</ElementType>
<ElementType name="Item">
</ElementType>
<ElementType name="Invoice">
<element type="Item">
<sql:relationship
key-relation="Orders"
key="OrderID"
foreign-relation="[Order Details]"
foreign-key="OrderID"/>
</element>
</ElementType>
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Until now, all of the schema examples in this module have mapped the schema
to a single table or view. However, it is common for a schema to map to
multiple tables in the underlying database. You achieve this type of mapping by
using the sql:relationship annotation. You can map data from related tables by
including the sql:relationship annotation and listing fields from a related table
as one of the following:
A nested element
An attribute
Specifying Keys Using the sql:relationship Annotation
In the annotated XDR Schema, you use the sql:relationship annotation to nest
the schema elements hierarchically. You can base the hierarchy on the primary
key and foreign key relationships among the underlying tables to which the
elements map. You must identify the following information when specifying
the sql:relationship annotation:
The primary table
The primary key field in the primary table
The foreign table
The foreign key field in the foreign table
To provide this information, specify the following attributes with the
relationship element.
Attribute Description
Key-relation Primary table
Key Primary key column
foreign-relation Foreign table
foreign-key Foreign key column
Topic Objective
To show how an annotated
schema can contain
references to multiple
database tables.
Lead-in
In many cases, the
annotated schema must
base its data on more than
one table.
32 Module 6: Using Mapping Schemas
In the following example, the annotated schema describes Invoice and Item
elements. Each invoice can have a number of items, so each <Invoice> element
can contain nested <Item> elements.
In the database, the Orders and Order Details tables are related by using the
OrderID column. In the annotated schema, the join is expressed in the
sql:relationship annotation.
<?xml version="1.0"?>
<Schema
xmlns="urn:schemas-microsoft-com:xml-data"
xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<ElementType name="Invoice" sql:relation="Orders">
<AttributeType name="InvoiceID"/>
<AttributeType name="InvoiceDate"/>
<attribute type="InvoiceID" sql:field="OrderID"/>
<attribute type="InvoiceDate" sql:field="OrderDate"/>
<element type="Item">
<sql:relationship
key-relation="Orders"
key="OrderID"
foreign-relation="[Order Details]"
foreign-key="OrderID"/>
</element>
</ElementType>
<ElementType name="Item" sql:relation="[Order Details]">
<AttributeType name="ProductID"/>
<AttributeType name="Qty"/>
<attribute type="ProductID" sql:field="ProductID"/>
<attribute type="Qty" sql:field="Quantity"/>
</ElementType>
</Schema>
The sql:relationship annotation uses the names of the underlying
database tables and columns, not the XML element and attribute names.
XML documents generated by using this schema and an XPath of Invoice
will have the following form:
<Invoice InvoiceID="10248" InvoiceDate="1996-07-04T00:00:00">
<Item ProductID="11" Qty="12" />
<Item ProductID="42" Qty="10" />
<Item ProductID="72" Qty="5" />
</Invoice>
<Invoice InvoiceID="10249" InvoiceDate="1996-07-05T00:00:00">
<Item ProductID="14" Qty="9" />
<Item ProductID="51" Qty="40" />
</Invoice>
If the primary key is composed of multiple columns, specify values with
a space between them. There is positional mapping between the values
specified for the multicolumn key and the corresponding foreign key.
Example
Note
Note
Module 6: Using Mapping Schemas 33
Controlling XML Document Nesting
Use the sql:key-fields annotation when the relationship
annotation does not provide primary keys
<ElementType name="InvoiceEmployee" sql:key-
fields="OrderID">
<element type="Employee">
<sql:relationship
key-relation="Orders"
key="EmployeeID"
foreign-relation="Employees"
foreign-key="EmployeeID"/>
</element>
</ElementType>
<ElementType name="Employee">
</ElementType>
<ElementType name="InvoiceEmployee" sql:key-
fields="OrderID">
<element type="Employee">
<sql:relationship
key-relation="Orders"
key="EmployeeID"
foreign-relation="Employees"
foreign-key="EmployeeID"/>
</element>
</ElementType>
<ElementType name="Employee">
</ElementType>
*****************************ILLEGAL FOR NON-TRAINER USE******************************
When two tables are related in a schema, the sql:relationship annotation may
not contain all of the information necessary to uniquely identify rows in the
source database. This situation occurs if the required hierarchy in the XML
document does not match a one-many relationship in the source database.
Using the sql:key-fields Annotation to Define a Primary
Key
When the key for the primary key table is not specified in the sql:relationship
annotation, use the sql:key-fields annotation to explicitly define it.
For example, consider a document that lists invoices and the employees who
created them. Each <Invoice> element contains an <Employee> element.
Examining the underlying database implies a join between the
Orders.EmployeeID and Employees.EmployeeID fields, and this is correct. The
corresponding sql:relationship annotation for this join is:
<sql:relationship
key-relation="Orders" key="EmployeeID"
foreign-relation="Employees" foreign-key="EmployeeID"/>
When the SQLOLEDB Provider creates the XML elements, it needs
information about how to uniquely identify the records in the Orders table.
Because the sql:relationship annotation does not provide this information in this
case, incorrect XML will resultthe Employee child elements will be
incorrectly nested.
To correct this problem, use the sql:key-fields annotation after the
sql:relationship annotation. This specifies the key field (or fields) for the
underlying tables.
Use the sql:key-fields annotation for all tables, even if you do not need it
to correct the problem shown here. It makes the schema more self-documenting.
Topic Objective
To explain the sql:key-fields
annotation.
Lead-in
When two tables are related
in a schema, the
sql:relationship annotation
might not contain all of the
information necessary to
uniquely identify rows in the
source database.
Tip
34 Module 6: Using Mapping Schemas
The following example shows a complete schema.
<?xml version="1.0"?>
<Schema
xmlns="urn:schemas-microsoft-com:xml-data"
xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<ElementType
name="InvoiceEmployee"
sql:relation="Orders"
sql:key-fields="OrderID">
<AttributeType name="InvoiceID"/>
<attribute type="InvoiceID" sql:field="OrderID"/>
<element type="Employee">
<sql:relationship
key-relation="Orders"
key="EmployeeID"
foreign-relation="Employees"
foreign-key="EmployeeID"/>
</element>
</ElementType>
<ElementType name="Employee" sql:relation="Employees">
<AttributeType name="EmployeeID"/>
<AttributeType name="LastName"/>
<attribute type="EmployeeID" sql:field="EmployeeID"/>
<attribute type="LastName" sql:field="LastName"/>
</ElementType>
</Schema>
The following example shows output from the preceding schema.
<InvoiceEmployee InvoiceID="10256">
<Employee EmployeeID="3" LastName="Chor" />
</InvoiceEmployee>
<InvoiceEmployee InvoiceID="10251">
<Employee EmployeeID="3" LastName="Chor" />
</InvoiceEmployee>
<InvoiceEmployee InvoiceID="10253">
<Employee EmployeeID="3" LastName="Chor" />
</InvoiceEmployee>
If data is extracted by using this schema without the sql:key-fields annotation,
the following incorrectly nested XML fragment is produced:
<InvoiceEmployee InvoiceID="10256" />
<InvoiceEmployee InvoiceID="10251" />
<InvoiceEmployee InvoiceID="10253">
<Employee EmployeeID="3" LastName="Chor" />
<Employee EmployeeID="3" LastName="Chor" />
<Employee EmployeeID="3" LastName="Chor" />
</InvoiceEmployee>
Example
Example
Delivery Tip
Be sure to point out which
output is correct and which
is incorrect.
Module 6: Using Mapping Schemas 35
Filtering Data
sql:limit-field and sql:limit-value annotations
Apply to table defined in foreign-relation
<ElementType name="Item"> </ElementType>
<ElementType name="FullPriceItems">
<element type="Item"
sql:limit-field="Discount"
sql:limit-value="0">
<sql:relationship
key-relation="Orders" key="OrderID"
foreign-relation="[Order Details]
foreign-key="OrderID"/>
</element>
</ElementType>
<ElementType name="Item"> </ElementType>
<ElementType name="FullPriceItems">
<element type="Item"
sql:limit-field="Discount"
sql:limit-value="0">
<sql:relationship
key-relation="Orders" key="OrderID"
foreign-relation="[Order Details]
foreign-key="OrderID"/>
</element>
</ElementType>
*****************************ILLEGAL FOR NON-TRAINER USE******************************
You can filter the rows returned from a query based on one or more values. Use
sql:limit-field and sql:limit-value annotations to identify the database column
that contains the limiting values, and to specify a specific limiting value to be
used.
Using the sql:limit-field Annotation
Use the sql:limit-field annotation to filter information that is returned based on
the value of a column in the database. You must use the sql:limit-field
annotation on an element or attribute that has a relationship specified. Use the
sql:limit-value annotation to specify the limited value in the column specified in
a sql:limit-field annotation.
In effect, the sql:limit-field and sql:limit-value annotations act like a WHERE
clause in SQL of the following form:
WHERE foreign-relation.limit-field = limit-value
Topic Objective
To show how the sql:limit-
field and sql:limit-value
annotations can be used to
restrict data used in the
query.
Lead-in
A developer may limit the
rows returned from a query
based on a limiting value, by
using the sql:limit-field and
sql:limit-value annotations.
36 Module 6: Using Mapping Schemas
The following example is a schema that uses the sql:limit-field and sql:limit-
value annotations to restrict output to only those items that have a zero
discount.
<?xml version="1.0"?>
<Schema
xmlns="urn:schemas-microsoft-com:xml-data"
xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<ElementType name="FullPriceItems" sql:relation="Orders">
<AttributeType name="InvoiceID"/>
<AttributeType name="InvoiceDate"/>
<attribute type="InvoiceID" sql:field="OrderID"/>
<attribute type="InvoiceDate" sql:field="OrderDate"/>
<element type="Item"
sql:limit-field="Discount"
sql:limit-value="0">
<sql:relationship
key-relation="Orders" key="OrderID"
foreign-relation="[Order Details]"
foreign-key="OrderID"/>
</element>
</ElementType>
<ElementType name="Item" sql:relation="[Order Details]">
<AttributeType name="ProductID"/>
<AttributeType name="Qty"/>
<AttributeType name="Discount"/>
<attribute type="ProductID" sql:field="ProductID"/>
<attribute type="Qty" sql:field="Quantity"/>
<attribute type="Discount" sql:field="Discount"/>
</ElementType>
</Schema>
You specify filtering by string equality. There are no relational operators
such as < or >. This annotation is suitable for coding relationships between
tables where the relationships are simple (based on column equality) and fixed.
For example, there is no provision to pass a parameter to the schema above to
change the sql:limit-value annotation to some other string value.
Example
Note
Module 6: Using Mapping Schemas 37
Lab 6.2: Mapping Multiple Tables
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Objectives
After completing this lab, you will be able to create a mapping schema that
maps XML data to multiple tables.
Prerequisites
Before working on this lab, you must understand:
XDR Schema syntax.
XML-SQL annotations for multiple tables.
ADO development by using Microsoft Visual Basic Scripting Edition.
Lab Setup
To complete this lab, you need a computer running Windows 2000 Server, with
SQL Server 2000 and Internet Explorer 5.5 or later installed.
Scenario
The business partners of the Northwind Traders organization require a more
descriptive format for catalog listings. This new format must include categories.
You will modify the existing schemas and annotate them to include the product
categories.
Estimated time to complete this lab: 30 minutes
Topic Objective
To introduce the lab.
Lead-in
In this lab, you willcreate
more complex mapping
schemas with multiple
tables.
Explain the lab objectives.
38 Module 6: Using Mapping Schemas
Exercise 1
Creating a Mapping Schema with Multiple Tables
In this exercise, you will create a mapping schema that uses two tables. This
will demonstrate how more complex schemas can be mapped.
Scenario
Northwind Traders wants to publish its product catalog with all of the
<Product> elements grouped within <Category> elements.
The following is a sample catalog listing:
<Catalog>
<Category ID="1" Name="Beverages">
<Product ID="1" Name="Chai" />
<Product ID="2" Name="Chang" />
</Category>
<Category ID="2" Name="Condiments">
</Category>
</Catalog>
The <Category> element maps to the Categories table in the Northwind traders
database, and the <Product> element maps to the Products table.
The attribute/column mappings for <Category> are listed in the following table.
Attribute Database column
ID CategoryID
Name CategoryName
The attribute/column mappings for <Product> are listed in the following table.
Attribute Database column
ID ProductID
Name ProductName
QuantityPerUnit QuantityPerUnit
UnitPrice UnitPrice
InStock UnitsInStock
OnOrder UnitsOnOrder
Discontinued Discontinued
The column Products.CategoryID is a foreign key to Category.CategoryID.
Module 6: Using Mapping Schemas 39
To edit the annotated schema
The file ProductSchema2.xml in the folder <install folder>\
Labs\Lab06\Solution contains a solution to this procedure.
1. Open the file ProductSchema2.xml with Notepad from the folder
<install directory>\Labs\Lab06\Starter. This file contains an XDR Schema
for the <Product> and <Category> elements. This schema has not yet been
annotated.
Add the xml-sql namespace to the <Schema> element by adding the
attribute xmlns:sql="urn:schemas-microsoft-com:xml-sql".
2. Add sql:relation annotations to map the <Product> element to the Products
table, and the <Category> element to the Categories table.
3. Add sql:field annotations to map the attributes in the <Product> and
<Category> elements to the appropriate database columns. For details, see
the tables at the beginning of this exercise.
4. In the definition of the <Category> element, find the <element> element
with a type attribute of Product. In this definition of the nested Product
element, add a <sql:relationship> annotation with the attributes listed in
the following table.
Attribute Value
key-relation Categories
key CategoryID
foreign-relation Products
foreign-key CategoryID
5. Save the file.
To test the mapping schema
1. If you have already completed Lab 6.1, Using Mapping Schemas, the
virtual root Lab06 already exists. If you have not already done so, run the
scripting host file CreateRoot.vbs in the folder <install folder>\Labs\Lab06
to create the virtual root.
2. The template file ProductTemplate2.xml has been provided in the folder
<install folder>\Labs\Lab06\Solution to test the schema. This template file
generates a document with an XPath expression /Category and root element
of <Catalog>. To see the generated document, open the following URL with
Internet Explorer:
http://localhost/Lab06/templates/ProductTemplate2.xml
40 Module 6: Using Mapping Schemas
Exercise 2
Annotating Key Fields
In this exercise, you will use the key-fields annotation.
Scenario
The schema for the product catalog document has changed. Although
Northwind Traders still requires category information in its product document,
the category information is to be held as a child element of the <Product>
element.
The same element and attributes are present in the document, and have the same
mapping to the database tables and columns as in Exercise 1.
The following is a sample of the catalog in the new format:
<Catalog>
<Product ID="1" Name="Chai"
QuantityPerUnit="10 boxes x 20 bags" UnitPrice="18"
InStock="39" OnOrder="0" Discontinued="0" >
<Category ID="1" Name="Beverages"/>
</Product>
<Product ID="2" Name="Chang"
QuantityPerUnit="24 - 12 oz bottles" UnitPrice="19"
InStock="17" OnOrder="40" Discontinued="0" >
<Category ID="1" Name="Beverages"/>
</Product>
</Catalog>
To edit the annotated schema
The file ProductSchema3.xml in the folder <install folder>\
Labs\Lab06\Solution contains a solution to this procedure.
1. Open the file ProductSchema3.xml with Notepad from the directory
<install directory>\Labs\Lab06\Starter. This file contains an XDR Schema
for the <Product> and <Category> elements. This schema is not yet
annotated.
Add the xml-sql namespace to the <Schema> element by adding the
attribute xmlns:sql="urn:schemas-microsoft-com:xml-sql".
2. Add sql:relation annotations to map the <Product> element to the Products
table, and the <Category> element to the Categories table.
3. Add sql:field annotations to map the attributes in the <Product> and
<Category> elements to the appropriate database columns. For details, see
the tables at the beginning of Exercise 1.
Module 6: Using Mapping Schemas 41
4. In the definition of the <Product> element, find the <element> element with
a type attribute of Category. In this definition of the nested
<Category>element, add a sql:relationship annotation with the following
attributes.
Attribute Value
key-relation Products
key CategoryID
foreign-relation Categories
foreign-key CategoryID
5. Add a sql:key-fields annotation to the <Product> element to identify the
key field for this table as ProductID. This is required because this
information cannot be inferred from the sql:relationship annotation.
To test the mapping schema
1. If you have already completed Lab 6.1 or Exercise 1 of this lab, the virtual
root Lab06 already exists. If you have not already done so, run the scripting
host file CreateRoot.vbs from the folder <install folder>\Labs\Lab06 to
create the virtual root.
2. The template file ProductTemplate3.xml has been provided in the folder
<install folder>\Labs\Lab06\Solution to test the schema. This template file
generates a document with an XPath expression /Product and a root
element of <Catalog>. To see the generated document, open the following
URL with Internet Explorer:
http://localhost/Lab06/templates/ProductTemplate3.xml
42 Module 6: Using Mapping Schemas
Annotating an Existing Schema
Using Constants
Excluding Fields
Mapping ID, IDREF, and IDREFS Attributes
Specifying Data Types
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Until now, the schemas you have examined have been specifically designed to
extract XML data from SQL Server. In reality, you might need to use an
existing schema that defines a business document that you need to exchange
with your trading partners.
This section discusses issues that arise when an existing schema document must
be mapped to data in a SQL Server database.
Topic Objective
To introduce the topics in
this section.
Lead-in
In this section, we will
discuss some of the major
issues facing developers
who need to map existing
XDR Schemas to SQL
Server data.
Module 6: Using Mapping Schemas 43
Using Constants
Use the sql:is-constant annotation to create constant
elements
<ElementType name="Items" sql:is-constant="1">
<element type="Item"/>
</ElementType>
<ElementType name="Item" sql:relation="[Order
Details]">
...
</ElementType>
<ElementType name="Items" sql:is-constant="1">
<element type="Item"/>
</ElementType>
<ElementType name="Item" sql:relation="[Order
Details]">
...
</ElementType>
*****************************ILLEGAL FOR NON-TRAINER USE******************************
By default, every element and attribute in an annotated schema must map to a
table or column in the database. However, schemas often contain an element or
attribute that does not map to any database table or column, but still appears in
the XML document.
For example, the root element of a document is usually defined in the schema,
although it does not necessarily map to a field in the database. Similarly, a
collection of elements (such as Item) may be contained within a container
element (such as Items). These are called constant elements. To create a
constant element, you can specify the sql:is-constant annotation to the
ElementType element. This takes a Boolean value (0 meaning false, and
1 meaning true).
The following table describes the values that you can assign to the sql:is-
constant annotation.
Boolean value Result
0 (False) The element must be mapped to a field in the database. This is
the default setting.
1 (True) The element appears in the resulting document as a constant. It is
not mapped to a field in the database.
Topic Objective
To explain the sql:is-
constant annotation.
Lead-in
You might want to create an
element in the schema that
contains a constant that is
not connected to any
database table or column.
This can be done with the
sql:is-constant annotation.
44 Module 6: Using Mapping Schemas
Using the sql:is-constant Annotation
You can use the sql:is-constant annotation to add a top-level element root
element to the XML document, or to create container elements elsewhere in the
XML document.
The following example shows a constant element <Items> around a set of
<Item> elements.
<?xml version="1.0"?>
<Schema
xmlns="urn:schemas-microsoft-com:xml-data"
xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<ElementType name="Items" sql:is-constant="1">
<element type="Item"/>
</ElementType>
<ElementType name="Item" sql:relation="[Order Details]">
<AttributeType name="InvoiceID"/>
<AttributeType name="ProductID"/>
<AttributeType name="Qty"/>
<attribute type="InvoiceID" sql:field="OrderID"/>
<attribute type="ProductID" sql:field="ProductID"/>
<attribute type="Qty" sql:field="Quantity"/>
</ElementType>
</Schema>
The following example shows output from the preceding schema with an XPath
expression of Items:
<Items>
<Item InvoiceID="10248" ProductID="11" Qty="12" />
<Item InvoiceID="10248" ProductID="42" Qty="10" />
<Item InvoiceID="10248" ProductID="72" Qty="5" />
<Item InvoiceID="10249" ProductID="14" Qty="9" />
</Items>
Example
Module 6: Using Mapping Schemas 45
Excluding Fields
Using the sql:map-field Annotation
<ElementType name="Item" sql:relation="[Order Details]">
<AttributeType name="InvoiceID"/>
<AttributeType name="ProductID"/>
<AttributeType name="Qty"/>
<AttributeType name="TransferStatus"/>
<attribute type="InvoiceID" sql:field="OrderID"/>
<attribute type="ProductID" sql:field="ProductID"/>
<attribute type="Qty" sql:field="Quantity"/>
<attribute type="TransferStatus" sql:map-field="0"/>
</ElementType>
<ElementType name="Item" sql:relation="[Order Details]">
<AttributeType name="InvoiceID"/>
<AttributeType name="ProductID"/>
<AttributeType name="Qty"/>
<AttributeType name="TransferStatus"/>
<attribute type="InvoiceID" sql:field="OrderID"/>
<attribute type="ProductID" sql:field="ProductID"/>
<attribute type="Qty" sql:field="Quantity"/>
<attribute type="TransferStatus" sql:map-field="0"/>
</ElementType>
*****************************ILLEGAL FOR NON-TRAINER USE******************************
The purpose of an annotated schema is not only to generate XML documents
from SQL server, but also to define the elements and attributes you want to use
in your XML documents. Some elements might be optional in the XDR Schema
and do not map to any fields in the database.
You can use the sql:map-field annotation to cause SQL Server to ignore any
optional fields in the schema that do not map to data in the database.
Using the sql:map-field Annotation
Similar to the sql:is-constant annotation, the sql:map-field annotation takes a
Boolean value where 0 represents false and 1 represents true. This annotation is
valid only on an <attribute>, <element>, or <ElementType> with text-only
content (content=textOnly). The annotation is not valid on an <element> or
<ElementType> that maps to a table.
Unlike the sql:is-constant annotation, in the sql:map-field annotation elements
and attributes that are unmapped do not appear in the output XML document.
The following table describes the values that you can assign to the sql:map-field
annotation.
Boolean value Result
0 (False) The element is not mapped to a field in the database, and will
not be generated in the resulting XML document.
1 (True) The element is mapped to a field in the database. This is the
default setting.
Topic Objective
To show how to use the
sql:map-field annotation to
exclude an XML element in
the output document.
Lead-in
Elements in the schema can
be excluded from the output
document by setting the
sql:map-field annotation to
0.
46 Module 6: Using Mapping Schemas
In the following example schema, the TransferStatus attribute is declared as
part of the annotated XML Schema but does not appear in the output XML and
is not mapped to a database column.
<?xml version="1.0"?>
<Schema
xmlns="urn:schemas-microsoft-com:xml-data"
xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<ElementType name="Item" sql:relation="[Order Details]">
<AttributeType name="InvoiceID"/>
<AttributeType name="ProductID"/>
<AttributeType name="Qty"/>
<AttributeType name="TransferStatus"/>
<attribute type="InvoiceID" sql:field="OrderID"/>
<attribute type="ProductID" sql:field="ProductID"/>
<attribute type="Qty" sql:field="Quantity"/>
<attribute type="TransferStatus" sql:map-field="0"/>
</ElementType>
</Schema>
Example
Module 6: Using Mapping Schemas 47
Mapping ID, IDREF, and IDREFS Attributes
Using ID, IDREF, and IDREFS Attributes
Using sql:id-prefix for ID Prefixes
<ElementType name="Invoice">
<AttributeType name="InvoiceID"
dt:type="id"
sql:id-prefix="in-"/>
...
<ElementType name="Invoice">
<AttributeType name="InvoiceID"
dt:type="id"
sql:id-prefix="in-"/>
...
<ElementType name="Item">
<AttributeType name="InvoiceID"
dt:type="idref"
sql:id-prefix="in-"/>
...
<ElementType name="Item">
<AttributeType name="InvoiceID"
dt:type="idref"
sql:id-prefix="in-"/>
...
*****************************ILLEGAL FOR NON-TRAINER USE******************************
As an alternative to nesting elements within other elements, you can map the
contents of several tables to elements that appear at the same level in the output
document. To relate the information in the tables, you can use ID, IDREF, and
IDREFS attributes, defined by the XML data types namespace (urn:schemas-
microsoft-com:datatypes).
Using ID, IDREF, and IDREFS Attributes
ID attributes correspond to primary keys. IDREF attributes correspond to
foreign keys, representing the many reference in a one-many relationship.
IDREFS attributes have no exact match in a relational database, but are used to
define the one end of a one-many relationship.
You can use the Document Object Model (DOM) with applications to navigate
from one set of elements to another by using the nodeFromID() method.
The value of an ID, IDREF, or IDREFS attribute must be a named
token. (For example, integer value 101 cannot be an ID value.)
Topic Objective
To explain how ID, IDREF,
and IDREFS attributes are
introduced in an annotated
schema.
Lead-in
ID, IDREF, and IDREFS
values can be generated
from the database. The
sql:id-prefix annotation is
used to ensure that ID
values from each table are
unique.
Delivery Tip
This section assumes that
students already have
knowledge of these attribute
types and the DOM
programming model. This
section should act as a
refresher.
Note
48 Module 6: Using Mapping Schemas
Using sql:id-prefix for ID Prefixes
In the XML document, the values of ID type attributes must be distinct within
the whole document. However, in a database, ID attribute values are usually
unique within a particular table.
You can use the sql:id-prefix annotation to automatically attach a different
prefix to each set of ID attribute values, thus ensuring uniqueness within the
document.
<?xml version="1.0"?>
<Schema
xmlns="urn:schemas-microsoft-com:xml-data"
xmlns:dt="urn:schemas-microsoft-com:datatypes"
xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<ElementType name="Invoice" sql:relation="Orders">
<AttributeType name="InvoiceID"
dt:type="id" sql:id-prefix="in_"/>
<AttributeType name="InvoiceDate"/>
<attribute type="InvoiceID" sql:field="OrderID"/>
<attribute type="InvoiceDate" sql:field="OrderDate"/>
</ElementType>
<ElementType name="Item" sql:relation="[Order Details]">
<AttributeType name="InvoiceID"
dt:type="idref" sql:id-prefix="in_"/>
<AttributeType name="ProductID"/>
<attribute type="InvoiceID" sql:field="OrderID"/>
<attribute type="ProductID" sql:field="ProductID"/>
</ElementType>
<ElementType name="InvoicesItems" sql:is-constant="1">
<element type="Item"/>
<element type="Invoice"/>
</ElementType>
</Schema>
Example
Module 6: Using Mapping Schemas 49
This schema creates mappings for two sets of elements. In the database, the
corresponding tables have a one-many relationship through Orders.OrderID,
and [Order Details].OrderID.
The InvoiceID attribute of the <Invoice> element is defined with a data type of
ID because it is the primary key, and is given an ID prefix of in_. The <Item>
element has an OrderID attribute, which is declared as an IDREF (foreign
key).
To act as a container, the <InvoicesItems> element contains all of the titles and
publishers elements. Because this is not mapped to any table in the database, it
is marked as a constant.
The following is sample output from this schema:
<InvoicesItems>
<Item InvoiceID="in_10285" ProductID="1" />
<Item InvoiceID="in_10294" ProductID="1" />
<Invoice InvoiceID="in_10248"
InvoiceDate="1996-07-04T00:00:00" />
<Invoice InvoiceID="in_10249"
InvoiceDate="1996-07-05T00:00:00" />
</InvoicesItems>
Delivery Tip
For simplicity, the example
shows only one SQL prefix.
50 Module 6: Using Mapping Schemas
Specifying Data Types
Using the sql:datatype Annotation
Support for binary data included with SQL Server
Support for all other SQL types added with the XML for
SQL update
*****************************ILLEGAL FOR NON-TRAINER USE******************************
The XML-datatypes namespace (urn:schemas-microsoft-com:datatypes)
provides a type attribute that you can use in a schema to define the XML data
type of an element or attribute. To match this to the appropriate SQL data type,
the XML-SQL namespace (urn:schemas-microsoft-com:xml-sql) provides the
sql:datatype annotation. You can use both attributes in a schema to ensure that
the retrieved data is mapped to the correct data type.
Using the sql:datatype Annotation
By default, you can use the sql:datatype annotation to explicitly define the data
type for binary fields, such as text or image columns. The XML-datatypes
namespace defines all such fields as bin.base64, and therefore the sql:datatype
annotation must be used to coerce the data to the correct data type. For
example, the following element declaration could be used in a schema:
<ElementType name="Employee" sql:relation="Employees">
<AttributeType name="EID"/>
<AttributeType name="fname"/>
<AttributeType name="lname"/>
<AttributeType name="photo" dt:type="bin.base64"/>
<attribute type="EID" sql:field="EmployeeID"/>
<attribute type="fname" sql:field="FirstName"/>
<attribute type="lname" sql:field="LastName"/>
<attribute type="photo" sql:field="Photo"
sql:datatype="image"/>
</ElementType>
Topic Objective
To describe how to use the
sql:datatype annotation.
Lead-in
The XML-DataTypes
namespace provides the
type attribute for XML data
types. You can use the
XML-SQL namespace
datatype annotation to
define SQL data types.
Module 6: Using Mapping Schemas 51
Defining Other SQL Data Types
If you have installed the XML for SQL update, you can assign other built-in
SQL data types (such as varchar and integer) to the sql:datatype annotation.
For example, the following element definition could be used to explicitly define
the data types of all fields.
<ElementType name="Employee" sql:relation="Employees">
<AttributeType name="EID"/>
<AttributeType name="fname"/>
<AttributeType name="lname"/>
<AttributeType name="photo" dt:type="bin.base64"/>
<attribute type="EID" sql:field="EmployeeID"
sql:datatype="integer"/>
<attribute type="fname" sql:field="FirstName"
sql:datatype="varchar(20)"/>
<attribute type="lname" sql:field="LastName"
sql:datatype="varchar(30)"/>
<attribute type="photo" sql:field="Photo"
sql:datatype="image"/>
</ElementType>
Delivery Tip
The XML for SQL update is
discussed fully in Module 7,
XML for SQL Tools.
Example
52 Module 6: Using Mapping Schemas
Lab 6.3: Annotating an Existing Schema
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Objectives
After completing this lab, you will be able to annotate an existing XDR
Schema.
Prerequisites
Before working on this lab, you must understand:
XDR Schema syntax.
XML-SQL annotations for multiple tables.
ADO development by using Visual Basic Scripting Edition.
Lab Setup
To complete this lab, you need a computer running Windows 2000 Server, with
SQL Server 2000 and Internet Explorer 5.5 installed.
Scenario
Northwind Traders wants to publish information about the buying habits of
each of its customers for internal use by its marketing department. An XML
Schema has already been developed. Your task is to map this schema to
elements of the database and generate a document.
The root element is <MarketingInfo>, which contains a single <Info> element.
The <Info> element contains three independent sets of elements:
The <Customer> element describes customers.
The <Product> element describes products in the catalog.
The <Invoice> element describes invoices raised by customers. Each
<Invoice> element contains a set of <Item> elements. Each <Item> element
describes one item in the invoice.
Topic Objective
To introduce the lab.
Lead-in
In this lab, you will annotate
an existing XDR Schema.
Explain the lab objectives.
Module 6: Using Mapping Schemas 53
The element sets are related through ID fields. Each of these fields has a distinct
prefix to ensure uniqueness across the document. The Customer ID attributes
have a prefix of cu_. The Product ID attributes have a prefix of pr_, and
the invoice ID attributes have a prefix of in_.
The following is an abbreviated sample of the data:
<MarketingInfo>
<Info>
<Customer ID="cu_ALFKI"
Company="Alfreds Futterkiste"
Contact="Maria Anders"
DirectMarketing="1"/>
<Customer ID="cu_ANATR"
Company="Ana Trujillo Emparedados y helados"
Contact="Ana Trujillo"
DirectMarketing="1"/>
<Product ID="pr_1" Name="Chai" />
<Product ID="pr_10" Name="Ikura" />
<Invoice ID="in_10248" Date="1996-07-04T00:00:00">
<Item ProductID="pr_11" Quantity="12" UnitPrice="14" />
</Invoice>
<Invoice ID="in_10249" Date="1996-07-05T00:00:00">
<Item ProductID="pr_14" Quantity="9" UnitPrice="18.6" />
<Item ProductID="pr_51" Quantity="40" UnitPrice="42.4"/>
</Invoice>
</Info>
</MarketingInfo>
54 Module 6: Using Mapping Schemas
The mapping between the elements and attributes of the XML document to the
database is as shown in the following tables.
The <Customer> element maps to the Customers table as follows.
Attribute Database column
ID CustomerID
Company CompanyName
Contact ContactName
DirectMarketing Not mapped to a database
column. See below.
The DirectMarketing attribute is a flag used within the marketing department.
It does not correspond to any column in the database, and in this exercise you
will not retrieve data for this attribute.
The <Product> element is mapped to the Products table as follows.
Attribute Database column
ID ProductID
Name ProductName
The <Invoice> element maps to the Orders table as follows.
Attribute Database column
ID OrderID
Date OrderDate
The <Item> element maps to the [Order Details] table as follows.
Attribute Database column
ProductID ProductID
Quantity Quantity
Unit Price UnitPrice
Estimated time to complete this lab: 30 minutes
Module 6: Using Mapping Schemas 55
Exercise 1
Annotating the Existing Schema
In this exercise, you will take the existing XDR Schema and provide mappings
to the Northwind Traders database. You will use the sql:relation, sql:field, and
sql:relationship annotations to map the elements and attributes to the underlying
database. You will also use sql:is-constant and sql:map-field annotations to
provide constant elements and specify unmapped elements. In addition, you
will use the id-prefix annotation to specify unique prefix values for IDs.
To add annotations to the existing schema
The file MarketingSchema1xml in the folder <install folder>\
Labs\Lab06\Solution contains a solution to this procedure.
1. Open the schema file MarketingSchema1.xml with Notepad from the
directory <install directory>\Labs\Lab06\Starter.
2. Add the xml-sql namespace to the <Schema> element.
3. Add the appropriate sql:relation, sql:field, and sql:relationship
annotations as necessary.
4. Annotate the <Info> element as a constant by using sql:is-constant.
5. Annotate the DirectMarketing attribute of the <Customer> element with
sql:map-field so that it is not mapped to a database column.
6. Add sql:id-prefix annotations to the ID attributes of the <Customer>,
<Invoice>, and <Products> tables, specifying the appropriate prefix for each
(cu_, in_, or pr_). Add a sql:id-prefix annotation to the ProductID
attribute of <Item>, specifying the pr_ prefix.
To test the schema
If you have already completed Lab 6.1, Using Mapping Schemas, or Lab
6.2, Mapping Multiple Tables, the virtual root Lab06 already exists. If
you have not already done so, run the scripting host file CreateRoot.vbs in
the folder <install folder>\Labs\Lab06 to create the virtual root. A template
has been provided in the file MarketingTemplate1.xml in the directory
<install directory>\Labs\Lab06\Starter.You can test the schema by
accessing following URL:
http://localhost/Lab06/templates/MarketingTemplate1.xml
56 Module 6: Using Mapping Schemas
Best Practices
Use schemas to represent business documents
Explicitly specify sql:key-fields when a relationship is
used
Disable caching when developing and testing
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Consider the following best practices when using annotated schemas.
Use Schemas to Represent Business Documents
Schemas are important because they define the documents that your
applications will generate. By adding annotations to a schema, you can
encapsulate the mapping between these documents and the underlying database.
Explicitly Specify sql:key-fields when a Relationship is
Used
The sql:relationship annotation, which specifies the relationship between two
database tables, is not enough to identify the primary key column(s) in all cases.
Get into the habit of specifying the sql:key-fields annotation.
Disable Caching when Developing and Testing
To ensure that the most up-to-date version of the schema is used in a
development environment, make sure that caching is disabled.
Topic Objective
To describe best practices
for using annotated
schemas.
Lead-in
You should consider the
following best practices
when using annotated
schemas.
Module 6: Using Mapping Schemas 57
Review
Using Mapping Schemas
Using Schemas to Retrieve Data
Mapping Multiple Tables
Annotating an Existing Schema
*****************************ILLEGAL FOR NON-TRAINER USE******************************
1. What are the purposes of the sql:relation and sql:field annotations?
The sql:relation annotation specifies the database table to which an
element in the schema is bound. The sql:field annotation specifies a
database column to which an element or attribute in the schema is
bound.
2. Name the four attributes of the sql:relationship annotation and state the
purpose of each attribute.
sql:key-relation Primary table
sql:key Primary key column(s)
sql:foreign-relation Foreign table
sql:foreign-key Foreign key columns(s)
3. List three ways of accessing data through a mapping schema.
An ADO application.
An IIS template query.
An IIS schema query.
4. Explain the purpose of the sql:id-prefix annotation.
The sql:id-prefix annotation is used to supply unique textual prefixes
for key values that are derived from different database tables.
Topic Objective
To reinforce module
objectives by reviewing key
points.
Lead-in
The review questions cover
some of the key concepts
taught in the module.
THIS PAGE INTENTIONALLY LEFT BLANK
Contents
Overview 1
Modifying Data with Updategrams 2
Lab 7.1: Using Updategrams 17
Inserting XML Data with the Bulk Load
Facility 22
Lab 7.2: Bulk Loading XML Data 31
Best Practices 34
Review 36
Module 7: XML for SQL
Tools
Information in this document is subject to change without notice. The names of companies,
products, people, characters, and/or data mentioned herein are fictitious and are in no way intended
to represent any real individual, company, product, or event, unless otherwise noted. Complying
with all applicable copyright laws is the responsibility of the user. No part of this document may
be reproduced or transmitted in any form or by any means, electronic or mechanical, for any
purpose, without the express written permission of Microsoft Corporation. If, however, your only
means of access is electronic, permission to print one copy is hereby granted.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
2001 Microsoft Corporation. All rights reserved.
Microsoft, ActiveX, BackOffice, BizTalk, MSDN, MS-DOS, SQL Server, Visual Basic, Visual
C++, Visual InterDev, Visual J++, Visual Studio, Windows, Windows Media, Windows NT, and
Windows 2000 are either registered trademarks or trademarks of Microsoft Corporation in the
U.S.A. and/or other countries.
Other product and company names mentioned herein may be the trademarks of their respective
owners.
Module 7: XML for SQL Tools iii
Instructor Notes
This module provides students with an understanding of Updategrams and
XML Bulk Load functionality provided in the XML for SQL Web Update.
After completing this module, students will be able to:
Insert, delete, and update data by using Updategrams.
Load Extensible Markup Language (XML) data into SQL Server by using
the XML Bulk Load facility.
Materials and Preparation
This section provides the materials and preparation tasks that you need to teach
this module.
Required Materials
To teach this module, you need Microsoft PowerPoint file 2091a_07.ppt.
Preparation Tasks
To prepare for this module, you should:
Read all of the materials for this module.
Complete the labs.
Presentation:
90 Minutes
Lab:
45 Minutes
iv Module 7: XML for SQL Tools
Module Strategy
Use the following strategy to present this module:
Modifying Data with Updategrams
Point out that an Updategram is conceptually a specialized form of template.
Emphasize the use of Updategrams to enable full data modification over
HTTP in a SQLISAPI virtual directorybased application. This means that
you can build a full data-enabled Web solution without any Active Server
Pages (ASP) code.
Inserting XML Data with the Bulk Load Facility
Emphasize that when inserting large volumes of data into SQL Server tables
the Bulk Load facility is more efficient than OpenXML. This is because the
Bulk Load facility reads data as a stream, allowing inserts to begin before
the entire XML document has been read.
Module 7: XML for SQL Tools 1
Overview
Modifying Data with Updategrams
Inserting XML Data with the Bulk Load Facility
*****************************ILLEGAL FOR NON-TRAINER USE******************************
In this module, you will learn how to use Updategrams to modify data, and how
to use the XML Bulk Load facility.
After completing this module, you will be able to:
Insert, delete, and update data by using Updategrams.
Load Extensible Markup Language (XML) data into SQL Server by using
the XML Bulk Load facility.
To enable support for Updategrams and XML bulk load functionality in
SQL Server 2000, you must download and install XML for SQL Web Update
from the MSDN Web site at http://msdn.microsoft.com
Topic Objective
To provide an overview of
the module topics and
objectives.
Lead-in
In this module, you will learn
about the additional
functionality available in the
XML for SQL Web Update.
For Your Information
You can download the XML
for SQL Web Update from
the MSDN Web site at
http://msdn.microsoft.com
2 Module 7: XML for SQL Tools
Modifying Data with Updategrams
Using an Updategram to Modify Data
Structure of an XML Updategram
Mapping Updategram Values to SQL Data
Inserting Data with an Updategram
Deleting Data with an Updategram
Updating Data with an Updategram
Using Parameters with an Updategram
Using Updategrams from a Client Application
*****************************ILLEGAL FOR NON-TRAINER USE******************************
In this section, you will see how to use Updategrams to insert, update, and
delete data in a Microsoft SQL Server
2000 database.
Topic Objective
To introduce the topics in
this section.
Lead-in
In this section, we will
discuss the use of
Updategrams to insert,
delete, and update data.
Module 7: XML for SQL Tools 3
Using an Updategram to Modify Data
Shipping Co.
Supplier
INSERT
UPDATE
DELETE
XML delivery data
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Similar to template files, Updategrams are XML documents that you can
submit as commands to SQL Server over a Microsoft ActiveX Data Objects
(ADO) or Hypertext Transfer Protocol (HTTP) connection. The main difference
is that templates are used to retrieve data, while Updategrams are used to
modify data.
Use an Updategram for data modifications that must be:
Performed from a Web site that is based on a SQL Internet Server
Application Programming Interface (SQLISAPI). In this case, templates or
mapping schemas could be used to retrieve data, and Updategrams could be
used to insert, update, or delete data.
Submitted by an organization to a trading partner over the Internet.
For example, a supplier could send a delivery request to a shipping company by
submitting an Updategram that inserts a record into a Deliveries table.
Topic Objective
To describe scenarios
where you can use
Updategrams to modify
data.
Lead-in
You can use Updategrams
for data modification in a
number of different
scenarios.
4 Module 7: XML for SQL Tools
Structure of an XML Updategram
Specify the xml-updategram namespace
Mark transactions within the <sync> element
Specify before and after images of data
<root xmlns:updg="urn:schemas-microsoft-com:xml-
updategram">
<updg:sync [mapping-schema=mapping schema]>
<updg:before>
XML Fragment
</updg:before>
<updg:after>
XML Fragment
</updg:after>
</updg:sync>
</root>
<root xmlns:updg="urn:schemas-microsoft-com:xml-
updategram">
<updg:sync [mapping-schema=mapping schema]>
<updg:before>
XML Fragment
</updg:before>
<updg:after>
XML Fragment
</updg:after>
</updg:sync>
</root>
*****************************ILLEGAL FOR NON-TRAINER USE******************************
An Updategram specifies what the XML data looks like now and what it will
look like after the Updategram is executed.
Specifying the xml-Updategram Namespace
Updategrams must reference the Microsoft xml-Updategram namespace
(schemas-microsoft-com:xml-Updategram). This namespace defines the
elements and attributes that are used in an Updategram.
You can reference the xml-Updategram namespace by adding an xmlns
attribute declaration in the root element of the Updategram, as shown in the
following example.
<root xmlns:updg="urn:schemas-microsoft-com:xml-Updategram">
Marking Transactions Within the <sync> Element
An Updategram contains one or more <sync> elements. Each <sync> element
can contain multiple inserts, updates, or deletes. The failure of one operation in
the sync element will cause all other modifications in the same <sync> element
to fail.
However, in an Updategram that contains multiple <sync> elements, the failure
of one <sync> element does not affect the other <sync> elements in the
document.
Specifying before and after Images of the Data
Represent each data modification by using a <updg:before> and <updg:after>
element pair. The <updg:before> element contains an image of the data before
the update. The <updg:after> element contains an image of the data after the
update.
Topic Objective
To introduce Updategrams.
Lead-in
An Updategram is similar to
a template, but is used for
different purposes.
Example
Module 7: XML for SQL Tools 5
Mapping Updategram Values to SQL Data
Using Default Mapping
Identical names assumed
Can be attribute-centric, element-centric, or mixed
Specifying a Mapping Schema
Specify a mapping-schema attribute for the <sync>
element
*****************************ILLEGAL FOR NON-TRAINER USE******************************
You can resolve XML elements and attributes in a before or after element of an
Updategram to the corresponding SQL Server data in two ways.
Using a Default Mapping
If no schema is specified, SQL Server will apply a default (or implicit) mapping
between the XML data in the Updategram and the data in the database.
Consider the following default mapping rules:
Elements that contain attributes or child elements map to table names.
XML attributes and child elements map to database columns that have the
same name as the attribute or element.
The following Updategram modifies the ProductName column of the Products
table:
<productupdate
xmlns:updg="urn:schemas-microsoft-com:xml-Updategram">
<updg:sync >
<updg:before>
<Products ProductID="1">
<ProductName>Chai</ProductName>
</Products>
</updg:before>
<updg:after>
<Products ProductID="1">
<ProductName>Tea</ProductName>
</Products>
</updg:after>
</updg:sync>
</productupdate>
Topic Objective
To describe how to resolve
XML data in an Updategram
to SQL Server data.
Lead-in
You can resolve the XML
data in an Updategram by
using a default mapping, or
by specifying a mapping
schema.
Example
6 Module 7: XML for SQL Tools
Specifying a Mapping Schema
Instead of relying on the default mapping, you can explicitly specify a mapping
schema that maps XML data to SQL Server data.
To specify a mapping schema, add a mapping-schema attribute to the <sync>
element in the Updategram.
<updg:sync mapping-schema="schema path">
Productschema.xml is a schema file that maps XML data to SQL Server data.
<productupdate
xmlns:updg="urn:schemas-microsoft-com:xml-Updategram">
<updg:sync mapping-schema="c:\productschema.xml">
<updg:before>
<Product ProductCode="1">
<ProductName>Chai</ProductName>
</Products>
</updg:before>
<updg:after>
<Product ProductCode="1">
<ProductName>Tea</ProductName>
</Products>
</updg:after>
</updg:sync>
</productupdate>
Syntax
Example
Module 7: XML for SQL Tools 7
Inserting Data with an Updategram
Inserting a Row
Specify an after image of the data
Inserting IDENTITY Values
Use the at-identity attribute for IDENTITY columns
Use returnid to retrieve the value used
Generating a GUID
Use the guid attribute
*****************************ILLEGAL FOR NON-TRAINER USE******************************
You can use Updategrams to insert rows into a database. This is useful when
you must send an XML document to a SQL Server virtual directory, or when
you must insert an XML data island on a Web page into a database.
Inserting a Row
You use the <updg:after> processing instruction element to specify the data to
be inserted. This element is paired with an empty <updg:before> element, as
shown in the following example.
<newproduct
xmlns:updg="urn:schemas-microsoft-com:xml-Updategram">
<updg:sync>
<updg:before>
</updg:before>
<updg:after>
<Products ProductID="101">
<ProductName>Finest Scotch Whisky</ProductName>
</Products>
</updg:after>
</updg:sync>
</newproduct>
If the table contains columns that are not specified in the Updategram, the
default values for those columns are inserted. If no default values are defined,
SQL Server attempts to insert NULL. If NULL values are not permitted in the
column, an error occurs and the entire insertion is cancelled.
You can insert multiple rows in a single <sync> element by declaring an XML
element for each row to be inserted.
Topic Objective
To describe how to perform
INSERT operations with an
Updategram.
Lead-in
You can use an
Updategram to insert rows
into a database.
Example
8 Module 7: XML for SQL Tools
Inserting IDENTITY Values
When a table contains an IDENTITY column, SQL Server automatically
generates the value of the column for all new records. You can insert an
IDENTITY value by using the at-identity attribute, and retrieve it by using the
returnid attribute. This is shown in the following example.
<AddOrder
xmlns:updg="urn:schemas-microsoft-com:xml-Updategram">
<updg:sync>
<updg:before>
</updg:before>
<updg:after updg:returnid="x">
<Orders updg:at-identity="x"
CustomerID="ALFKI"
OrderDate="01/01/01"/>
<Order_x0020_Details OrderID="x"
ProductID="11"
UnitPrice="$100.0"
Quantity="1"
Discount="0.0" />
</updg:after>
</updg:sync>
</AddOrder>
In this example, a row is inserted into the Orders and Order Details tables. The
Order Details table contains an IDENTITY column, which is represented in the
Updategram by the at-identity value x. The value that SQL Server
automatically inserts is returned in the Updategram response.
<AddOrder
xmlns:updg="urn:schemas-microsoft-com:xml-Updategram">
<returnid>
<x>11078</x>
</returnid>
</AddOrder>
Generating a GUID
You can generate globally unique identifier (GUID) by specifying a guid
attribute. For example, the following Updategram inserts a new customer with a
unique identifier.
<NewCustomer
xmlns:updg="urn:schemas-microsoft-com:xml-Updategram">
<updg:sync >
<updg:before>
</updg:before>
<updg:after>
<Customers updg:guid="x">
<CustomerID>x</CustomerID>
<CustomerName>Graeme</CustomerName>
</Customers>
</updg:after>
</updg:sync>
</NewCustomer>
Example
For Your Information
In the Updategram example,
the space in Order Details is
represented by the encoded
value _x0020_. This is
necessary because the
space character is illegal in
XML. The UnitPrice value is
converted to the SQL Server
data type money by
prefixing it with a $
character. This is required
for all money columns
unless you use a schema
declaring the column as
XML data type fixed.14.4.
Example
For Your Information
This example will not work
with the Northwind Traders
database.
Module 7: XML for SQL Tools 9
Deleting Data with an Updategram
Specify a before image of the data
Each before child element must identify a single record
<DeleteProduct
xmlns:updg="urn:schemas-microsoft-com:xml-
updategram">
<updg:sync>
<updg:before>
<Products ProductID="101"/>
</updg:before>
<updg:after>
</updg:after>
</updg:sync>
</DeleteProduct>
<DeleteProduct
xmlns:updg="urn:schemas-microsoft-com:xml-
updategram">
<updg:sync>
<updg:before>
<Products ProductID="101"/>
</updg:before>
<updg:after>
</updg:after>
</updg:sync>
</DeleteProduct>
*****************************ILLEGAL FOR NON-TRAINER USE******************************
You can use Updategrams to delete data.
Deleting a Single Record
Deleting a single record with an Updategram involves two easy steps:
1. First, specify a before image of the data. The contents of the before image
act like a SQL WHERE clause. Each element in the before element must
uniquely identify a single record to be deleted.
2. Specify an empty after image.
Topic Objective
To describe how to perform
DELETE operations with an
Updategram.
Lead-in
You can use an
Updategram to delete data
from the database.
10 Module 7: XML for SQL Tools
The following Updategram deletes any record in the Products table matching a
Product ID of 101:
<DeleteProduct
xmlns:updg="urn:schemas-microsoft-com:xml-Updategram">
<updg:sync>
<updg:before>
<Products ProductID="101"/>
</updg:before>
<updg:after>
</updg:after>
</updg:sync>
</DeleteProduct>
Deleting Multiple Records
You can use a single Updategram to delete multiple records. To do this, you
must specify a separate <updq:before> element for each record you want to
delete. If the <updq:before> element does not contain enough information to
uniquely identify a single record, the deletion will create an error condition. For
example, if more than one product has a Category value of 2, the following
element would cause an error:
<Products Category="2"/>
Example
Module 7: XML for SQL Tools 11
Updating Data with an Updategram
Specifying before and after Images of the Data
Updating Multiple Rows
Use the id attribute to match before and after elements
<UpdateProduct
xmlns:updg="urn:schemas-microsoft-com:xml-updategram">
<updg:sync >
<updg:before>
<Products ProductID="101"/>
</updg:before>
<updg:after>
<Products UnitPrice="$752.99"/>
</updg:after>
</updg:sync>
</UpdateProduct>
<UpdateProduct
xmlns:updg="urn:schemas-microsoft-com:xml-updategram">
<updg:sync >
<updg:before>
<Products ProductID="101"/>
</updg:before>
<updg:after>
<Products UnitPrice="$752.99"/>
</updg:after>
</updg:sync>
</UpdateProduct>
*****************************ILLEGAL FOR NON-TRAINER USE******************************
You can use Updategrams to update data in the database.
Specifying before and after Images of the Data
When you update records, you use the elements identified in the <updg:before>
element to specify which rows to update. You use the elements in the
<updg:after> element to specify the changes you want to make to the data.
Similar to DELETE operations, each element in the <updg:before> element
must identify a single row in the database.
The following Updategram could be used to change the price of product 101:
<UpdateProduct
xmlns:updg="urn:schemas-microsoft-com:xml-Updategram">
<updg:sync >
<updg:before>
<Products ProductID="101"/>
</updg:before>
<updg:after>
<Products UnitPrice="$102.99"/>
</updg:after>
</updg:sync>
</UpdateProduct>
Topic Objective
To describe how to perform
UPDATE operations with an
Updategram.
Lead-in
You can use an
Updategram to update data
in a database.
Example
12 Module 7: XML for SQL Tools
Updating Multiple Rows
When you update multiple rows, match the id attribute to the corresponding
before and after elements.
The following Updategram updates the CategoryID field for products 101
and 102:
<UpdateProducts
xmlns:updg="urn:schemas-microsoft-com:xml-Updategram">
<updg:sync >
<updg:before>
<Products updg:id="x" ProductID="101"/>
<Products updg:id="y" ProductID="102"/>
</updg:before>
<updg:after>
<Products updg:id="x" CategoryID="2"/>
<Products updg:id="y" CategoryID="2"/>
</updg:after>
</updg:sync>
</UpdateProducts>
Example
Module 7: XML for SQL Tools 13
Using Parameters with an Updategram
<UpdateProduct
xmlns:updg="urn:schemas-microsoft-com:xml-
updategram">
<updg:header>
<updg:param name="ProductID"/>
<updg:param name="NewCategory"/>
</updg:header>
<updg:sync >
<updg:before>
<Products ProductID="$ProductID"/>
</updg:before>
<updg:after>
<Products CategoryID="$NewCategory"/>
</updg:after>
</updg:sync>
</UpdateProduct>
<UpdateProduct
xmlns:updg="urn:schemas-microsoft-com:xml-
updategram">
<updg:header>
<updg:param name="ProductID"/>
<updg:param name="NewCategory"/>
</updg:header>
<updg:sync >
<updg:before>
<Products ProductID="$ProductID"/>
</updg:before>
<updg:after>
<Products CategoryID="$NewCategory"/>
</updg:after>
</updg:sync>
</UpdateProduct>
Declare parameters in <updg:header>
Assign parameters using $
*****************************ILLEGAL FOR NON-TRAINER USE******************************
As with templates, you can supply an Updategram with one or more parameters
to make it more flexible.
Declaring Parameters in the <header> Element
If you decide to use parameters, you must declare each parameter by using a
separate <param> element. All of the <param> elements must be nested within
the <header> element. The <header> and <param> elements are defined in the
xml-Updategram namespace.
Assigning a Parameter
To assign a parameter, you use the dollar sign ($) character within the <param>
element.
The following Updategram could be used to change the CategoryID of a
product:
<UpdateProduct
xmlns:updg="urn:schemas-microsoft-com:xml-Updategram">
<updg:header>
<updg:param name="ProductID"/>
<updg:param name="NewCategory"/>
</updg:header>
<updg:sync >
<updg:before>
<Products ProductID="$ProductID"/>
</updg:before>
<updg:after>
<Products CategoryID="$NewCategory"/>
</updg:after>
</updg:sync>
</UpdateProduct>
Topic Objective
To describe how to use
parameters in an
Updategram.
Lead-in
You can use parameters in
an Updategram.
Delivery Tip
Point out that parameters in
Updategrams are similar to
parameters in templates.
The main difference is that
the $ character is used in
Updategrams, while the @
character is used in
templates.
Example
For Your Information
Because the $ character is
used to indicate both
parameters and money
values, you cannot pass a
parameter of the type
money unless you use a
mapping schema to define
the field as dt:fixed.14.4.
14 Module 7: XML for SQL Tools
Using Updategrams from a Client Application
Submitting an Updategram Using an ADO 2.6 Command
Assign to CommandStream or CommandText
Publishing an Updategram in a Virtual Name
Access over HTTP similar to a template
POSTing an Updategram over HTTP
Must enable Updategram POST option
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Executing an Updategram is similar to executing a template.
Submitting an Updategram Using an ADO 2.6 Command
A client application can use an ADO 2.6 Command object to submit an
Updategram for execution in exactly the same way as a template.
Topic Objective
To describe how to use
Updategrams from a client.
Lead-in
Executing an Updategram is
similar to executing a
template.
Module 7: XML for SQL Tools 15
The following example shows how you can use ADO to execute an
Updategram:
Set objCmd = CreateObject("ADODB.Command")
ObjCmd.ActiveConnection = "Provider=SQLOLEDB; Data
Source=server1; Database=stock;Integrated Security=SSPI;"
SQLxml = "<PriceChange xmlns:updg='urn:schemas-microsoft-
com:xml-Updategram' >"
SQLxml = SQLxml & "<updg:sync >"
SQLxml = SQLxml & " <updg:before>"
SQLxml = SQLxml & " <Products ProductID='10' />"
SQLxml = SQLxml & "</updg:before>"
SQLxml = SQLxml & "<updg:after>"
SQLxml = SQLxml & "<Products UnitPrice='$125.99' />"
SQLxml = SQLxml & "</updg:after>"
SQLxml = SQLxml & "</updg:sync>"
SQLxml = SQLxml & "</PriceChange>"
Set objStrmUDgram = CreateObject("ADODB.Stream")
objStrmUDgram.Open
objStrmUDgram.WriteText SQLxml
objStrmUDgram.Position = 0
Set objCmd.CommandStream = objStrmUDgram
Set objStrmResponse = CreateObject("ADODB.Stream")
objStrmResponse.Open
objCmd.Properties("Output Stream").Value = objStrmResponse
objCmd.Execute , , 1024
msgbox objStrmResponse.ReadText
Publishing an Updategram in a Virtual Name
You can publish an Updategram in a template virtual name. The Updategram
can then be accessed over HTTP like any other template.
Consider that you have created an Updategram and saved it as AddOrder.xml in
a folder that is published as a virtual name called templates. If this virtual
name is published in a virtual directory named sales on a server named
webserver1, the URL used to execute the Updategram is:
http://webserver1/sales/templates/AddOrder.xml
Example
Example
16 Module 7: XML for SQL Tools
POSTing an Updategram over HTTP
You can submit an Updategram through an HTTP POST, either from a form on
a Web page or from an HTTP-aware client application.
The following HTML form could be used to POST an Updategram:
<body>
Enter the CustomerID and Name.
<form action="http://webserver1/sales" method="POST">
<B>Product ID:</B>
<input type=text name=CustomerID ><br><B>Price</B><input
type=text name=CustomerName >
<input type=hidden name=contenttype value=text/xml>
<input type=hidden name=template value='
<AddCust xmlns:updg="urn:schemas-microsoft-com:xml-
Updategram">
<updg:header>
<updg:param name="CustomerID"/>
<updg:param name="CustomerName" />
</updg:header>
<updg:sync>
<updg:before>
</updg:before>
<updg:after>
<Customers CustomerID="$CustomerID"
CustomerName="$CustomerName" />
</updg:after>
</updg:sync>
</AddCust>
'>
<p><input type="submit">
</form>
</body>
Enabling POSTed Updategrams
Before an Updategram can be POSTed, you must enable the option to allow
POST queries in the Configure SQL XML Support in IIS tool (where IIS
represents Microsoft Internet Information Services). In addition, you must
enable the Allow SQL= or Template=URL Queries option or the Allow
Posted Updategrams option. Using Allow Posted Updategrams limits the
level of access available over HTTP so that clients cannot execute queries in a
URL, thereby increasing security.
Example
Module 7: XML for SQL Tools 17
Lab 7.1: Using Updategrams
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Objectives
After completing this lab, you will be able to insert, delete, and update data by
using Updategrams.
Prerequisites
Before working on this lab, you must have:
Knowledge of how to publish an XML template in a virtual name.
Knowledge of how to submit data from an HTML form to a virtual root.
For More Information
Read the section Using Updategrams to Modify Data in the XML for SQL
Web Update documentation.
Using the Solution Files
This lab uses an IIS virtual directory that points to the folder <install folder>\
Labs\Lab07\Starter in order to process template files that contain Updategrams.
To run a Solution file, you must copy the file from the folder <install
folder>\Labs\Lab07\Solution to the folder <install folder>\Labs\Lab07\Starter.
Scenario
Data in the Northwind Traders database needs to be inserted, updated, and
deleted by a variety of applications. In this lab, you will create solutions that
use Updategrams to modify the data in the database.
Estimated time to complete this lab: 30 minutes
Topic Objective
To introduce the lab.
Lead-in
In this lab, you will create
and use Updategrams to
modify data in the Northwind
Traders database.
Explain the lab objectives.
18 Module 7: XML for SQL Tools
Exercise 1
Inserting Data Using an Updategram
In this exercise, you will create an Updategram to add data to the Northwind
Traders database.
Scenario
New customers and suppliers who use the Northwind Traders Web site need to
be able to register through their browsers. You will create an Updategram that
inserts the new customer and supplier data into the database.
To create a virtual root
Double-click the script CreateRoot.vbs in the folder <install folder>\
Labs\Lab07. This script creates a SQL Server virtual directory named
Lab07, with the templates virtual name updategrams.
To create an updategram to insert customer data
You can examine the solution for this procedure by viewing the file
InsertCustomer.xml in the folder <install folder>\Labs\Lab07\Solution.
1. Open the file InsertCustomer.xml with Microsoft Notepad from the folder
<install folder>\Labs\Lab07\Starter.
2. Between the <newcustomer> elements, add XML code to create an
updategram with the following features:
A <header> element containing three parameters named CustomerID,
CompanyName, and ContactName.
A sync element containing an empty <before> element and an <after>
element that will insert a record into the Customers table by using the
three parameters for the CustomerID, CompanyName, and
ContactName columns.
3. Save the file and close Notepad.
To use the customer updategram
1. Open the file AddCustomer.htm with Notepad from the folder
<install folder>\Labs\Lab07\Starter. Note that this page sends three
parameters to the InsertCustomer.xml Updategram.
2. Close Notepad and double-click AddCustomer.htm to open it with
Microsoft Internet Explorer.
3. Confirm that the Customer ID and Company Name fields are filled in for
you, and enter your own name in the Contact Name field.
4. Click Add Customer. An empty newcustomer XML document should be
returned. (Subsequent insertions of the same record will return an error
message because the CustomerID field is a primary key).
5. Close Internet Explorer, and use SQL Server Query Analyzer to confirm
that the data has been inserted into the Customers table in the Northwind
Traders database.
Module 7: XML for SQL Tools 19
To create an updategram to insert supplier data with an IDENTITY
column
You can examine the solution for this procedure by viewing the file
InsertSupplier.xml in the folder <install folder>\Labs\Lab07\Solution.
1. Open the file InsertSupplier.xml with Notepad from the folder
<install folder>\Labs\Lab07\Starter.
2. Between the <newsupplier> elements, add XML code to create an
updategram with the following features:
A header element containing two parameters named CompanyName
and ContactName.
A sync element containing an empty <before> element and an <after>
element that will insert a record into the Suppliers table. You should use
the at-identity attribute to insert a value into the SupplierID column,
and return the inserted value by using the returnid attribute.
3. Save the file and close Notepad.
To use the supplier updategram
1. Open the file AddSupplier.htm with Notepad from the folder
<install folder>\Labs\Lab07\Starter. Note that this page sends two
parameters to the InsertSupplier.xml Updategram.
2. Close Notepad and double-click AddSupplier.htm to open it with
Internet Explorer.
3. Confirm that the Company Name field is filled in for you, and enter your
own name in the Contact Name field.
4. Click Add Supplier. A newsupplier XML document containing a returnid
attribute with the IDENTITY value used should be returned.
5. Close Internet Explorer and use SQL Server Query Analyzer to confirm that
the data has been inserted into the Suppliers table in the Northwind Traders
database.
20 Module 7: XML for SQL Tools
Exercise 2
Deleting Data with an Updategram
In this exercise, you will create an Updategram to delete data from the
Northwind Traders database.
Scenario
Customers with no outstanding orders can remove themselves from the
Northwind Traders database over the Internet. You must develop an
Updategram that enables the deletion of a customer record.
To add a customer to the database
1. Run the script InsertCustomer.vbs from the folder Lab07\Starter.
2. Use SQL Server Query Analyzer to confirm that a customer with the
CustomerID PLACEHOLDER has been added to the Customers table in
the Northwind Traders database.
To create an updategram to delete a customer record
You can examine the solution for this procedure by viewing the file
DeleteCustomer.xml in the folder <install folder>\Labs\Lab07\Solution.
1. Open the file DeleteCustomer.xml with Notepad from the folder
<install folder>\Labs\Lab07\Starter.
2. Between the <deletecustomer> elements, add XML code to create an
Updategram that will delete the record from the Customers table with the
CustomerID value that is passed to the updategram as a parameter.
3. Save the file and close Notepad.
To use the deletecustomer updategram
1. Open the file RemoveCustomer.htm with Notepad from the folder <install
folder>\Labs\Lab07\Starter. Note that this page sends a CustomerID
parameter to the DeleteCustomer.xml Updategram.
2. Close Notepad and double-click RemoveCustomer.htm to open it with
Internet Explorer.
3. Confirm that the CustomerID field contains the value PLACEHOLDER,
and click Unregister Me. An empty deletecustomer XML document
should be returned.
4. Close Internet Explorer and use SQL Server Query Analyzer to confirm that
the data has been deleted from the customer table in the Northwind Traders
database.
Module 7: XML for SQL Tools 21
Exercise 3
Updating Data with an Updategram
In this exercise, you will create an Updategram to modify data in the Northwind
Traders database.
Scenario
Northwind Traders users need to be able to modify their customer details
through the Northwind Traders Web site. You must create an Updategram that
will allow customers to change their ContactName information.
To create an updategram to update the Customers table
You can examine the solution for this procedure by viewing the file
UpdateCustomer.xml in the folder <install folder>\Labs\Lab07\Solution.
1. Open the file UpdateCustomer.xml with Notepad from the folder
<install folder>\Labs\Lab07\Starter.
2. Between the <updatecustomer> elements, add XML code to create an
Updategram that accepts two parameters. The Updategram should update
the record from the Customers table with the CustomerID value that is
passed to the Updategram as the first parameter, by changing the
ContactName field to the value passed as the second parameter.
3. Save the file and close Notepad.
To use the updatecustomer updategram
1. Open the file UpdateCustomer.htm with Notepad from the folder
<install folder>\Labs\Lab07\Starter. Note that this page sends a
CustomerID parameter and a ContactName parameter to the
UpdateCustomer.xml Updategram.
2. Close Notepad and double-click UpdateCustromer.htm to open it with
Internet Explorer.
3. Confirm that the CustomerID field contains the value ALFKI, and type
your own name in the ContactName field.
4. Click Submit. An empty updatecustomer XML document should be
returned.
5. Close Internet Explorer and use SQL Server Query Analyzer to confirm that
the data has been updated in the Northwind Traders database.
22 Module 7: XML for SQL Tools
Inserting XML Data with the Bulk Load Facility
Bulk Loading XML Data Using the Bulk Load Facility
Using the SQLXMLBulkLoad Object
SQLXMLBulkLoad and Mapping Schemas
Bulk Load Options
Handling Bulk Load Errors
*****************************ILLEGAL FOR NON-TRAINER USE******************************
You use the Bulk Load facility to insert large volumes of XML data into
SQL Server tables. The Bulk Load facility provides a scriptable object to
programmatically read an XML file or stream. You then use a mapping schema
to insert the data into the appropriate tables in the database.
This section describes the use of the SQLXMLBulkLoad object, and discusses
issues involved in using this object to bulk load data.
Topic Objective
To introduce the topics in
this section.
Lead-in
You can use the Bulk Load
facility to insert large
volumes of XML data into
SQL Server.
Module 7: XML for SQL Tools 23
Bulk Loading XML Data Using the Bulk Load Facility
Supplier
Catalog
Retailer
Extranet
Bulk Load
facility
*****************************ILLEGAL FOR NON-TRAINER USE******************************
You can use the XML Bulk Load facility to import large volumes of XML data
into SQL Server.
For example, a retailer could download catalog data from a supplier in XML
format, and use a script to import the data into a local database.
Consider the following facts about the Bulk Load facility:
The Bulk Load facility can be used from any COM-aware programming
language, including Microsoft Visual Basic Scripting Edition (VBScript),
Visual Basic, Microsoft Visual C++, and Microsoft Visual J++.
Before importing XML data by using the Bulk Load facility, you must
define a mapping schema that maps the XML data to columns in the
SQL Server database.
The Bulk Load facility requires an OLE DB connection to SQL Server.
Topic Objective
To describe a scenario
where the Bulk Load facility
can be used.
Lead-in
You can use the XML Bulk
Load facility to import large
volumes of XML data into
SQL Server.
Delivery Tip
This slide builds
automatically to show a
catalog being downloaded
from a supplier and
imported into a retailer
database.
You can restart the build by
pressing the LEFT ARROW
key on your keyboard.
24 Module 7: XML for SQL Tools
Using the SQLXMLBulkLoad Object
Creating a SQLXMLBulkLoad Object
Loading Data Using the Execute Method
Mapping schema and XML source parameters
Set objBL=CreateOhect("SQLXMLBulkLoad.SQLXMLBulkLoad")
Set objBL=CreateOhect("SQLXMLBulkLoad.SQLXMLBulkLoad")
objBL.Execute "c:\productschema.xml", "c:\products.xml"
objBL.Execute "c:\productschema.xml", "c:\products.xml"
*****************************ILLEGAL FOR NON-TRAINER USE******************************
You can script the SQLXMLBulkLoad object to import XML data into
SQL Server. This provides a high-performance approach to loading XML data.
Creating a SQLXMLBulkLoad Object
You can instantiate the SQLXMLBulkLoad object in any COM-aware
language by using the ProgID SQLXMLBulkLoad.SQXMLBulkLoad. After
you have created the SQLXMLBulkLoad object, it must be connected to a
database by using one of the following two approaches:
Assign an OLE DB connection string to the ConnectionString property
Assign an existing ADO Command object to the ConnectionCommand
property.
Loading Data Using the Execute Method
XML data is loaded into the database by calling the Execute method of the
SQLXMLBulkLoad object. This method accepts the following two
parameters:
bstrSchemaFile A mapping schema used to map the XML data to tables in
the database
vDataFile A file or stream containing the XML data to be imported
The following example shows how you can use VBScript to import XML data
into a SQL Server database by using the SQLXMLBulkLoad object.
Dim objBL
Set objBL=CreateObject("SQLXMLBulkLoad.SQLXMLBulkLoad")
objBL.ConnectionString ="PROVIDER=sqloledb;" & _
"DATA SOURCE=server1;" & _
"INITIAL CATALOG=retaildb" & _
"INTEGRATED SECURITY=sspi;"
objBL.Execute "c:\productschema.xml", "c:\products.xml"
Topic Objective
To describe the
SQLXMLBulkLoad object.
Lead-in
You can script the
SQLXMLBulkLoad object to
import XML data into SQL
Server.
Example
Module 7: XML for SQL Tools 25
SQLXMLBulkLoad and Mapping Schemas
is-constant nodes are ignored
Elements with map-field = "0" are ignored
Optionally loaded into overflow-field column
Use the key-ordering rule with relationships
The primary key attribute in the parent should be
specified before the child element
If an explicit foreign key value is not specified in the child
element, the primary key from the parent will be inserted
*****************************ILLEGAL FOR NON-TRAINER USE******************************
The SQLXMLBulkLoad object interprets the annotations in the mapping
schema and loads the data accordingly. Each time an opening tag for an element
that corresponds to a table is read, a record is generated for that table. When the
closing tag for the element is read, the row is inserted into the database.
Using is-constant Annotations
If a node in the schema is assigned the attribute is-constant="1", the
SQLXMLBulkLoad object ignores the node and does not attempt to generate a
row for it. This annotation is commonly used for root elements or container
elements that do not map to data in the database.
Using map-fields Annotations
Data in the schema annotated with the attribute map-fields="0" are not
mapped to data in the database. The SQLXMLBulkLoad object ignores these
fields unless the parent element in the schema has an overflow-field annotation
specifying a column for unconsumed XML data. In this case, the data in the
unmapped field is inserted into the overflow column.
Using the Key-Ordering Rule
When a schema contains a hierarchical XML representation of a relationship
between SQL Server tables, the child element may not include the foreign key
value required in the corresponding table.
In any primary key table element containing a foreign key table element, the
primary key field should be declared before the child element. This allows the
SQLXMLBulkLoad object to insert the primary key from the parent element
into the foreign key column in the table represented by the child element.
If the child element contains a value for the foreign key field, the value in the
child element is inserted into the table. Otherwise, the primary key from the
parent table is used.
Topic Objective
To explain how the
SQLXMLBulkLoad object
handles annotations in
mapping schemas.
Lead-in
The SQLXMLBulkLoad
object interprets the
annotations in the mapping
schema.
26 Module 7: XML for SQL Tools
For example, the following XML document and schema could be used to bulk
load data into the Categories and Products tables. Because the <Product>
element does not include the CategoryID value, the primary key from the
<Category> element is used.
<?xml version="1.0"?>
<Catalog>
<Category CategoryID="1" CategoryName="Computers">
<Product ProductID="1" ProductName="Desktop Computer"/>
<Product ProductID="2" ProductName="Laptop Computer"/>
</Category>
<Category CategoryID="2" CategoryName="Monitors">
<Product ProductID="5" ProductName="15 inch Monitor"/>
<Product ProductID="6" ProductName="17 inch Monitor"/>
</Category>
</Catalog>
<Schema xmlns="urn:schemas-microsoft-com:xml-data"
xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<ElementType name="Catalog" sql:is-constant="1">
<element type="Category"/>
</ElementType>
<ElementType name="Category" sql:relation="Categories">
<AttributeType name="CategoryID"/>
<AttributeType name="CategoryName"/>
<attribute type="CategoryID" sql:field="CategoryID"/>
<attribute type="CategoryName" sql:field="CategoryName"/>
<element type="Product">
<sql:relationship
key-relation="Categories"
key="CategoryID"
foreign-key="CategoryID"
foreign-relation="Products"/>
</element>
</ElementType>
<ElementType name="Product" sql:relation="Products">
<AttributeType name="ProductID"/>
<AttributeType name="ProductName"/>
<attribute type="ProductID" sql:field="ProductID"/>
<attribute type="ProductName" sql:field="ProductName"/>
</ElementType>
</Schema>
For information about how other annotations are handled by the
SQLXMLBulkLoad object, see the XML for SQL documentation.
Example Document
Example Schema
Note
Module 7: XML for SQL Tools 27
Bulk Load Options
Generate the database schema
SGDropTables property
SchemaGen property
SGUseID property
Assign NULL with the KeepNulls property
Assign IDENTITY values with the KeepIdentity property
*****************************ILLEGAL FOR NON-TRAINER USE******************************
The SQLXMLBulkLoad object has a number of properties that you can use to
control its behavior. This provides a number of useful options when bulk
loading data.
Generating the Database Schema
By default, the SQLXMLBulkLoad object is used to import data into existing
database tables. You can change this behavior by setting the following
properties:
SchemaGen
Setting this property to True causes the tables mapped by the schema to be
created, if they do not already exist.
SGDropTables
Setting this property to True (together with the SchemaGen property)
causes all tables mapped by the schema to be dropped and recreated.
SGUseID
Setting this property to True causes primary key constraints to be created
based on any id attributes defined in the schema.
In addition, setting the BulkLoad property to False causes the creation of the
tables mapped in the schema, without importing any data.
Assigning NULL Values
By default, if a column in a table has no matching element or attribute in the
XML document that is being loaded, the default value for the column is
inserted. If no default value is defined, NULL is inserted. Setting the
KeepNulls property to True causes a NULL value to be inserted for unmapped
columns, even if they have default values defined.
Topic Objective
To explain some of the
options available when
using the SQLXMLBulkLoad
object.
Lead-in
You can use a number of
properties to set options
when using the
SQLXMLBulkLoad object.
28 Module 7: XML for SQL Tools
Assigning IDENTITY Values
By default, any values in an XML document that map to IDENTITY columns
are inserted instead of the automatically generated IDENTITY value. If you
want to ignore the value in the XML document and use the system-generated
value, you must set the KeepIdentity property to False.
The KeepIdentity property is an all-or-nothing option. If you set
KeepIdentity to False, automatic values are generated for all tables with
IDENTITY columns.
Example
The following bulk load process drops and recreates the table, inserts NULL for
any unspecified columns, and uses the system-generated IDENTITY values:
Dim objBL
Set objBL=CreateObject("SQLXMLBulkLoad.SQLXMLBulkLoad")
With objBL
.ConnectionString ="PROVIDER=sqloledb;" & _
"DATA SOURCE=server1;" & _
"INITIAL CATALOG=retaildb" & _
"INTEGRATED SECURITY=sspi;"
.SchemaGen=True
.SGDropTables=True
.KeepNulls=True
.KeepIdentity=False
End With
objBL.Execute "c:\productschema.xml", "c:\products.xml"
Note
Module 7: XML for SQL Tools 29
Handling Bulk Load Errors
Logging Errors
Always specify the ErrorLogFile property
Maintaining Relational Integrity
IgnoreDuplicateKeys property
CheckConstraints property
Using Transactions
Transaction property
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Be aware that errors can occur during a bulk load process. Errors can happen as
a result of incorrectly defined schemas, invalid XML data, or violations of the
databases referential integrity. You can control the way the
SQLXMLBulkLoad object handles errors in a number of ways.
Logging Errors
You should always specify the ErrorLogFile property when using the
SQLXMLBulkLoad object. This causes any errors to be logged to a text file.
Maintaining Referential Integrity
To enforce referential integrity, you can control error-handling behavior by
using the following properties:
IgnoreDuplicateKeys
By default, an attempt to insert a duplicate primary key results in an error,
and the entire bulk load operation is stopped. Setting the
IgnoreDuplicateKeys property to True results in the failure of the
individual insertion without stopping the entire import.
CheckConstraints
Setting the CheckConstraints property to True causes primary/foreign key
constraints to be enforced during insertions. Constraint violation results in
an error.
Topic Objective
To discuss how to handle
bulk load errors.
Lead-in
Errors can occur during a
bulk load process.
30 Module 7: XML for SQL Tools
Using Transactions
You can use transactions to ensure the robustness of the import process. When a
transaction is used, the bulk load operation either completely succeeds or
completely fails.
The following properties are used to control transactional behavior of the
SQLXMLBulkLoad object:
Transaction
Setting this property to True causes a transaction to be used. Each row is
stored in a temporary file until the bulk load process is complete. The entire
import process is rolled back if the operation fails.
TempFilePath
This property is used to control the location of the temporary file used when
the Transaction property is set to True. When bulk loading on the local
computer, this should be a local file path. When importing data to a remote
server a UNC path (\\servername\sharename) must be used.
Using transactions causes a performance overhead. As a result, a
transactional importing of a large volume of data will take longer than a non-
transactional importing of the same data.
The following example shows how you can handle errors when using the
SQLXMLBulkLoad object.
Dim objBL
Set objBL=CreateObject("SQLXMLBulkLoad.SQLXMLBulkLoad")
With objBL
.ConnectionString ="PROVIDER=sqloledb;" & _
"DATA SOURCE=server1;" & _
"INITIAL CATALOG=retaildb" & _
"INTEGRATED SECURITY=sspi;"
.ErrorLogFile="c:\importerrors.log"
.IgnoreDuplicateKeys=True
.CheckConstraints=True
.Transaction=True
.TempFilePath="\\Server1\TempShare"
End With
objBL.Execute "c:\productschema.xml", "c:\products.xml"
Note
Example
Module 7: XML for SQL Tools 31
Lab 7.2: Bulk Loading XML Data
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Objectives
After completing this lab, you will be able to load XML data into SQL Server
by using the XML Bulk Load facility.
Prerequisites
Before working on this lab, you must have an understanding of annotated
XML-Data Reduced (XDR) Schemas.
For More InformationRead the section Performing Bulk Load of
XML in the XML for SQL Web Update documentation.
Scenario
Some data in the Northwind Traders database must be regularly loaded from
XML files. For example, new employee records are loaded from XML
personnel records, and the catalog is updated by importing category and product
data from an XML catalog file.
Estimated time to complete this lab: 15 minutes
Topic Objective
To introduce the lab.
Lead-in
In this lab, you will load XML
data into SQL Server by
using the XML Bulk Load
facility.
Explain the lab objectives.
32 Module 7: XML for SQL Tools
Exercise 1
Importing Data from an XML File
In this exercise, you will use the XML Bulk Load facility to import employee
data from an XML file.
Scenario
When new employees join Northwind Traders, their employee details are stored
in a personnel database. After the employees initial training, these details are
exported to an XML file to be loaded into the Northwind Traders database.
To examine the schema and data files
1. Open the file PersonnelSchema.xml with Internet Explorer from the folder
<install folder>\Labs\Lab07\Starter. This file defines the schema for a list of
employees.
2. Open the file NewEmployees.xml with Internet Explorer from the folder
<install folder>\Labs\Lab07\Starter. This file contains a list of employees
based on the personnelschema.xml schema.
3. Close Internet Explorer.
To import the employee data by using the XML Bulk Load facility
You can examine a solution to this procedure by viewing the file
ImportEmployees.vbs in the folder <install folder>\Labs\Lab07\Solution.
1. Open the file ImportEmployees.vbs file with Notepad from the folder
Lab07\Starter. Note that a utility routine to identify the current directory is
provided.
2. Find the comment Add Your Code Here, and add code to do the following
tasks:
Instantiate the objBulkLoad variable as a SQLXMLBulkLoad object.
Set the ConnectionString property to connect the component to the
Northwind Traders database on the local server by using Integrated
Security.
Use the strSchemaFile and strXMLFile variables to execute the bulk
load process.
3. Save the file and close Notepad.
4. Double-click the script ImportEmployees.vbs to execute it.
5. Use SQL Server Query Analyzer to confirm that the records have been
imported into the Employees table in the Northwind Traders database.
Module 7: XML for SQL Tools 33
Exercise 2
Importing Data and Generating a Database Schema
In this exercise, you will import data by using the Bulk Load facility while
dropping the necessary tables and generating the database schema.
Scenario
The Northwind Traders catalog needs to be periodically updated. The new
catalog data is represented in an XML document, which must be imported into
the Categories and Products tables. The existing tables must be dropped and
recreated as part of the import process.
To examine the schema and data files
1. Open the file CatalogSchema.xml with Internet Explorer from the folder
<install folder>\Labs\Lab07\Starter. This file defines the schema for a list of
categories and products. (The data maps to tables named NewCategories
and NewProducts, respectively.)
2. Open the file CatalogData.xml with Internet Explorer from the folder
<install folder>\Labs\Lab07\Starter. This file contains a list of categories
and products based on the CatalogSchema.xml schema. (The large binary
fields are category pictures.)
3. Close Internet Explorer.
To import the catalog data and generate the database schema
You can examine a solution to this procedure by viewing the file
ImportCatalog.vbs in the folder <install folder>\Labs\Lab07\Solution.
1. Open the file ImportCatalog.vbs with Notepad from the folder
Lab07\Starter.
2. Find the comment Add Your Code Here, and add code to do the following
tasks:
Instantiate the objBulkLoad variable as a SQLXMLBulkLoad object.
Set the ConnectionString property to connect the component to the
Northwind Traders database on the local server by using Integrated
Security.
Set the appropriate properties to generate the database schema, dropping
existing tables if necessary.
Use the strSchemaFile and strXMLFile variables to execute the bulk
load process.
3. Save the file and close Notepad.
4. Double-click the script ImportCatalog.vbs to execute it.
5. Use SQL Server Query Analyzer to confirm that the records have been
imported into newly created NewCategories and NewProducts tables in the
Northwind Traders database.
34 Module 7: XML for SQL Tools
Best Practices
Consider Updategram concurrency issues
Allow POSTed Updategrams but not queries
Define data types for date/time or UUID fields
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Consider the following best practices when using Updategrams or the Bulk
Load facility.
Consider Updategram Concurrency Issues
When updating records with an Updategram, you might want to address
concurrency issues. SQL Server uses the information in the <updg:before>
element to prevent overwriting of changes made to records by other users since
the Updategram was submitted. You can control concurrency behavior by using
the following techniques:
Specify only the primary key in the <updg:before> element. This causes all
changes to the record by other users (other than deletion) to be overwritten.
Specify the primary key and any fields that are to be updated in the
<updg:before> element. Any changes made by other users to the fields
affected by the Updategram will cause the update to fail.
Specify all fields in the <updg:before> element. Changes made by other
users to any fields in the record will cause the update to fail.
Topic Objective
To describe best practices
for using Updategrams and
the Bulk Load facility.
Lead-in
Consider these best
practices when using
Updategrams or the Bulk
Load facility.
Module 7: XML for SQL Tools 35
Allow POSTed Updategrams
When you use an IIS virtual directory to publish a database, you can restrict the
application of POST to only allow Updategrams to be POSTed and not URL
queries. Restricting the use of POST to apply only to Updategrams provides a
higher level of security than allowing any query to be executed over HTTP
(although it does allow any update to be performed by using an Updategram).
To allow POSTed Updategrams, set the allow posted Updategrams option for
the virtual directory.
Define Data Types for Date/Time and UUID Fields
When defining schemas that will be used with the Bulk Load facility, any fields
that contain date/time or UUID values should be defined by using the XML
dt:type and sql:datatype attributes. This ensures that the correct data type is
entered into the database.
36 Module 7: XML for SQL Tools
Review
Modifying Data with Updategrams
Inserting XML Data with the Bulk Load Facility
*****************************ILLEGAL FOR NON-TRAINER USE******************************
1. You want to use an Updategram to modify data in a SQL Server database.
How can you map elements and attributes in the Updategram to tables and
columns in the database?
Use the default mapping, where the names of elements and attributes
must match the names of the corresponding tables and columns, or
specify a mapping schema.
2. How can you use an Updategram to insert a row into a table with an
IDENTITY column, and retrieve the identity value used in the HTTP
response?
Create an Updategram containing an <updg:after> element with no
corresponding <updg:before> element. Use the at-identity attribute to
insert the identity column, and the returnid attribute to receive the
inserted identity value.
3. How can you match multiple <updg:before> elements with their
corresponding <updg:after> elements?
Use the id attribute to assign a unique value to each element pair.
4. You want to use the Bulk Load facility to import data into a SQL Server
database. What properties should you set to ensure that the tables are
dropped and recreated?
SGDropTables and SchemaGen should both be set to TRUE.
Topic Objective
To reinforce module
objectives by reviewing key
points.
Lead-in
The review questions cover
some of the key concepts
taught in the module.