Sunteți pe pagina 1din 48

Tema 2C:

Using XML

Tema 2C: Using XML


Using the xml Data Type
Retrieving XML by Using FOR XML
Shredding XML by Using OPENXML
Introducing XQuery
Creating XML Indexes
Implementing XML Schemas

Lesson 1: Using the xml Data Type


What is XML?
What is the xml Data Type?
The Query, Value, and Exist Methods
The Modify Method
The Nodes Method

What is XML?
XML is a plain-text, Unicode-based meta-language
Represents both structured and semi-structured data
Not tied to any programming language, OS, or vendor

A sample XML document for a music store order:


<?xml version="1.0" encoding="iso-8859-1" ?>
<?xml-stylesheet href="orders.xsl"?>
<order id="ord123456">
<customer id="cust0921">
<first-name>Dare</first-name>
<last-name>Obasanjo</last-name>
<address>
<street>One Microsoft Way</street>
<city>Redmond</city>
<state>WA</state>
<zip>98052</zip>
</address>
</customer>
</order>

What is the xml Data Type?


Native data type for XML
Lets you store XML documents and fragments
Used for tables, variables, or parameters
Exposes methods to query and modify XML
-- usage within table definition
CREATE TABLE NewTable
( Col1 int primary key,
Col2 xml )
-- usage as local variable
declare @data xml
-- usage as parameter to stored procedure
CREATE PROCEDURE SaveData(@doc xml) AS ...

The Query, Value, and Exist Methods

Use query to return untyped XML

Use value to return a scalar value

SELECT
xmlCol.query(
Use exist
to check existence of value
'<InvoiceNumbers>
{
Bind
relational
columns and variables
for
$i in /InvoiceList/Invoice
return <InvoiceNo>
{number($i/@InvoiceNo)}
SELECT Invoices.query(
SELECT xmlCol.exist(
xmlCol.value(
</InvoiceNo>
'<Store>
'(/InvoiceList/Invoice/@InvoiceNo)[1]',
'/InvoiceList/Invoice[@InvoiceNo=1000]'
}
{sql:column("StoreName")}
)'int')
</InvoiceNumbers>')
</Store>')

The Modify Method

Insert adds child nodes to an XML document

Replace value of updates node in an XML doc

Delete removes a node from the XML document

SET xmlCol.modify(
@xmlDoc.modify(
SET
@xmlDoc.modify(
'insert
replace
element
value of
salesperson {"Bill"}
'delete
(/InvoiceList/Invoice/SalesPerson/text())[1]
as first
(/InvoiceList/Invoice/SalesPerson)[1]')
into "Ted"')
with
(/InvoiceList/Invoice)[1]')

The Nodes Method

Shreds XML variables into relational data

Requires the APPLY operator with XML columns

nCol.value('@ProductID', 'int')
SELECT nCol.value('../@OrderID[1]',
'int')
Product,
ID,
nCol.value('@Quantity', 'int')
Qty
nCol.value('@ProductID[1]',
'int')
FROM
@xmlOrder.nodes('/Order/LineItem')
Prod
AS
nTable(nCol)
FROM
Orders
CROSS APPLY OrderDoc.nodes('/Order/LineItem')
AS nTable(nCol)

Demonstration: Using the xml Data Type


In this demonstration, you will see how to:
Use the xml data type
Use the query, value, and exist methods
Bind relational columns
Use the modify method to insert, update, and delete XML
Use the nodes method

Notes Page Over-flow Slide. Do Not Print Slide.


See Notes pane.

Notes Page Over-flow Slide. Do Not Print Slide.


See Notes pane.

Lesson 2: Retrieving XML by Using FOR XML


Introduction to the FOR XML Clause
What are RAW Mode Queries?
What are AUTO Mode Queries?
What are EXPLICIT Mode Queries?
What are PATH Mode Queries?
Syntax for Retrieving Nested XML

Introduction to the FOR XML Clause




Extends SELECT syntax

Returns XML instead of rows and columns

Configurable to return attributes, elements, and schema

Benefits client applications that work with XML

Converted to XML

Database Server

Client Application

What are RAW Mode Queries?

XML representation of a rowset

Contains either elements or attributes

Optional root element and row element name

SELECT
FROM

Cust.CustomerID CustID, CustomerType, SalesOrderID


Customer Cust JOIN SalesOrderHeader [Order]
ON Cust.CustomerID = [Order].CustomerID
ORDER BY Cust.CustomerID
FOR XML RAW('Order'),
RAW ELEMENTS ROOT('Orders')
RAW,
<Orders>
<row
<row>
CustID="1" CustomerType="S" SalesOrderID="43860"/>
<row<Order><CustID>1</CustID><CustomerType>S</...
<CustID>1</CustID>
CustID="1" CustomerType="S" SalesOrderID="44501"/>
... </Order>
<CustomerType>S</CustomerType>
<SalesOrderID>43860</SalesOrderID>
...
</row>...
</Orders>

What are AUTO Mode Queries?


XML representation of data entities
Execute this query:
SELECT Cust.CustomerID,
OrderHeader.CustomerID,
OrderHeader.SalesOrderID,
OrderHeader.Status,
Cust.CustomerType
FROM Sales.Customer Cust, Sales.SalesOrderHeader OrderHeader
WHERE Cust.CustomerID = OrderHeader.CustomerID
ORDER BY Cust.CustomerID
FOR XML AUTO

This is the partial result:


<Cust CustomerID="1" CustomerType="S">
<OrderHeader CustomerID="1" SalesOrderID="43860"
<OrderHeader CustomerID="1" SalesOrderID="44501"
<OrderHeader CustomerID="1" SalesOrderID="45283"
<OrderHeader CustomerID="1" SalesOrderID="46042"
</Cust>
...

Status="5"
Status="5"
Status="5"
Status="5"

/>
/>
/>
/>

What are EXPLICIT Mode Queries?

Tabular representations of XML documents

Tag

Parent

Invoice!1!InvoiceNo

Invoice!1!Date!Element

NULL

43659

2001-07-01T00:00:00

NULL

43660

2001-07-02T00:00:00

Allow complete control of XML format

SELECT 11 AS
AS Tag,
Tag, NULL
NULL AS
AS Parent,
Parent,
SalesOrderID
SalesOrderID AS
AS [Invoice!1!InvoiceNo],
[Invoice!1!InvoiceNo],
OrderDate
OrderDate AS
AS [Invoice!1!Date!Element]
[Invoice!1!Date!Element]
FROM SalesOrderHeader
SalesOrderHeader
FOR XML EXPLICIT
Attribute
<Invoice InvoiceNo="43659">
<Date>2001-07-01T00:00:00</Date>
</Invoice>
<Invoice InvoiceNo="43660">...

Element

What are PATH Mode Queries?


Use XML Path Language (XPath) to specify XML format
Allow creation of nested data
Easier to use than EXPLICIT mode
SELECT EmployeeID "@EmpID",
FirstName "EmpName/First",
LastName
"EmpName/Last"
FROM
Person.Contact INNER JOIN Employee
ON Person.Contact.ContactID = Employee.ContactID
FOR XML PATH
<row EmpID="1">
<EmpName>
<First>Guy</First>
<Last>Gilbert</Last>
</EmpName>
</row>
...

Syntax for Retrieving Nested XML

AUTO mode produces only attributes or elements

Use inner FOR XML with TYPE clause to return xml data type

Combine EXPLICIT mode with UNION ALL

SELECT 1 Cust.CustomerID,
CustomerType,
SalesOrderID, Status
Name
AS Tag,
CategoryName,
NULL AS Parent,
...
FROM SalesOrderHeader
Customer
Cust SubCategoryName
JOIN SalesOrderHeader [Order]
(SELECT Name
Cust.CustomerID
= [Order].CustomerID
UNION ALLON
FROM
ProductSubCategory
SubCategory
ORDER
Cust.CustomerID
SELECTBY
2 WHERE
AS Tag, 1SubCategory.ProductCategoryID
AS Parent, ...
=
FOR
AUTO,
FROMXML
SalesOrderDetail
Category.ProductCategoryID
OD JOIN ...
AUTO ELEMENTS
FOR XML EXPLICIT
FOR XML AUTO, TYPE, ELEMENTS)
FROM
ProductCategory Category
<Cust
<Cust>
CustomerID="1"
CustomerType="S">
FOR XML AUTO
<CustomerID>1</CustomerID>
<Order
SalesOrderID="43860" Status="5"/>
<Invoice
InvoiceNo="43659">
<CustomerType>S</CustomerType>
<Order SalesOrderID="44501" Status="5"/>
<Date>2001-07-01T00:00:00</Date>
<Order>
...
<Category
CategoryName="Accessories">
<LineItem
ProductID="709">Bike Socks, M</LineItem>
</Cust>
<SalesOrderID>43860</SalesOrderID>
<SubCategory>
<LineItem
ProductID="711">Helmet, Blue</LineItem>
<Status>5</Status>... Racks</SubCategoryName>
<SubCategoryName>Bike
</Invoice>...
</SubCategory>...

Demonstration: Using FOR XML


In this demonstration, you will see how to:
Retrieve XML in RAW mode
Retrieve XML in AUTO mode
Retrieve XML in EXPLICIT mode
Retrieve XML in PATH mode

Notes Page Over-flow Slide. Do Not Print Slide.


See Notes pane.

Lesson 3: Shredding XML by Using OPENXML


Overview of Shredding XML Data
Stored Procedures for Managing In-Memory Node Trees
OPENXML Syntax
Syntax for Working with XML Namespaces

Overview of Shredding XML Data


1

XML document
received from
client

Create internal tree


representation by using
sp_xml_preparedocument

Process (or shred)


the data into tables

Use sp_xml_removedocument
to clean up memory tree

Use OPENXML to
retrieve rowset

Stored Procedures for Managing In-Memory Node Trees


Create tree by using sp_xml_preparedocument

Free memory by using sp_xml_removedocument

CREATE PROC ProcessOrder


@doc xml -- xml data
AS
-- Declare document handle
DECLARE @hdoc integer
-- Create memory tree
EXEC sp_xml_preparedocument @hdoc OUTPUT, @doc
-- Process Document
-- Remove memory tree
EXEC sp_xml_removedocument @hdoc

OPENXML Syntax
<Customer CustomerID="1" CustomerType="S">
<Order SalesOrderID="43860" Status="5"
OrderDate="2001-08-01T00:00:00">
<OrderDetail ProductID="761" Quantity="2"/>
<OrderDetail ProductID="770" Quantity="1"/>
</Order>
</Customer>

rowpattern identifies node level

Uses attributes as default

SELECT *
FROM OPENXML (@idoc, '/Customer/Order/OrderDetail', 1)
WITH (CustomerID int
'../../@CustomerID',
From
Customer
OrderID
int
'../@SalesOrderID',
element
OrderDate datetime '../@OrderDate',
ProdID
int
'@ProductID',
Quantity
int)
From Order
element
Defaults to Quantity attribute

From OrderDetail element

Syntax for Working With XML Namespaces


sp_xml_preparedocument accepts namespaces
Use namespace prefix in all XPath expressions
<Customer xmlns="urn:AW_NS" xmlns:o="urn:AW_OrderNS"
CustomerID="1" CustomerType="S">
<o:Order SalesOrderID="43860" Status="5"
OrderDate="2001-08-01T00:00:00">
<o:OrderDetail ProductID="761" Quantity="2"/>
<o:OrderDetail ProductID="770" Quantity="1"/>
</o:Order>
</Customer>
EXEC sp_xml_preparedocument @idoc OUTPUT, @doc,
<ROOT xmlns:rootNS="urn:AW_NS" xmlns:orderNS="urn:AW_OrderNS"/>'
SELECT * FROM OPENXML (@idoc,
'/rootNS:Customer/orderNS:Order/orderNS:OrderDetail')
WITH...

Demonstration: Using OPENXML to Shred XML


In this demonstration, you will see how to:
Use the OPENXML function
Shred XML by using elements only
Shred XML by using attributes or elements
Shred XML by using a colpattern parameter

Lesson 4: Introducing XQuery


What Is XQuery?
XQuery Basics
XQuery Expressions

What Is XQuery?

Query language to identify nodes in XML

Can query structured or semi-structured XML

/InvoiceList/Invoice[@InvoiceNo=1000]

FLWOR statements

Statement

Description

For

Iterate through sibling nodes

where

Apply filtering criteria to the iteration

order by

Sort values in returned resultset

return

Specify the XML to be returned

XQuery Basics
Sequences and QNames

Result of an XQuery expression is a sequence

All identifiers are QNames

Operators

Arithmetic comparison

General comparison

Value comparison

Node comparison

Node order comparison

Logical

if-then-else
if ( $A eq $B )
then <result>A</result>
else <result>B</result>

Comments
(: Comment text :)

XQuery Expressions
Primary expressions

Literals

Variable references

Function calls

Path expressions

child::Address/child::Country

Sequence expressions

Construct, filter and


combine sequences

Relative

Absolute

/Address/Country

declare @x xml
set @x = '<root>
<abc></abc>
<abc attrAbc="1"></abc>
<abc attrAbc="2"></abc>
</root>'
SELECT
@x.query('/root/abc[attrAbc]')

Demonstration: Using XQuery Expressions


In this demonstration, you will see how to:
Declare namespace and retrieve product XML data
Declare namespace and retrieve employment XML data

Lesson 5: Creating XML Indexes


What Are XML Indexes?
What are the Benefits of XML Indexes?
Types of XML Index

What are XML Indexes?

XML indexes can be created on xml data type columns


They index all tags, values and paths over the XML
instances in the column and benefit query performance

XML indexes fall into the following categories:


Primary XML index

Secondary XML index

What are the Benefits of XML Indexes?


Your application may benefit from an XML index when:
Queries on XML columns are common in your workload

Your XML values are relatively large and the retrieved parts
are relatively small

Types of XML Indexes


XML indexes fall into the following categories:
Primary XML index
Index scan or seek on the primary XML index
Secondary XML index
Index scan or seek on node table's PATH index
Index scan or seek on node table's PROPERTY index
Index scan or seek on node table's VALUE index

Demonstration: Creating XML Indexes


In this demonstration, you will see how to:
Record the performance statistics for an XML query
Create a primary XML index
Create a secondary XML index
Investigate the performance statistics for an XML query

Notes Page Over-flow Slide. Do Not Print Slide.


See Notes pane.

Lesson 6: Implementing XML Schemas


What Are XML Schemas?
XML Schema Validation
What Is an XML Schema Collection?
What is Typed and Untyped XML

What are XML Schemas?


XML Schema is an XML-based alternative to Document Type
Definition (DTD)
An XML schema describes the structure of XML document
The XML Schema language is also called XML Schema
Definition (XSD)

An XML schema provides the following:


Validation constraints

SQL Server validates the instance


Data type information

Schemas provide info about types of attributes and elements

XML Schema Validation


New XML Schema Validation Support in SQL 2012:
Type

Notes
XML Schemas support wildcard sections

Lax Validation Support

through the any, anyAttribute, and


anyType declarations
You can use the dateTime data type in

Full xs:dateTime Support

an XML schema to define date and time


data
You can use XML schemas to define

Union and List Types

data types that allow a limited set of


values to be assigned to multi-value
elements and attributes

What is an XML Schema Collection?

SQL Server provides native storage of XML data with


the xml data type

You can optionally associate XSD schemas with an xml


type through an XML schema collection
The XML schema collection does the following:
Stores the imported XML schemas

Validates XML instances

Types the XML data as it is stored in the database

What is Typed and Untyped XML?


Use untyped XML data type in the following situations:
You do not have a schema for your XML data
You have schemas, but dont want server to validate data
Use typed XML data type in the following situations:
You have schemas and want server to validate XML data
You want to take advantage of storage and query

optimizations based on type information


You want to take better advantage of type information

during compilation of your queries

Demonstration: Using Typed XML


In this demonstration, you will see how to:
Create an XML schema collection
Create a typed XML column
Insert valid and invalid data into a typed XML column

Lab: Using XML


Exercise 1: Mapping Relational Data and XML
Exercise 2: Storing XML Natively in the Database
Exercise 3: Using XQuery with XML Methods
Exercise 4: Creating XML Indexes

Logon information

Virtual machine

NYC-SQL-01

User name

Administrator

Password

P2ssw0rd

Estimated time: 60 minutes

Lab Scenario
Adventure Works currently generates order manifests by performing a query
in the AdventureWorks database. The organization intends to deploy a new
Pocket PCbased application to its warehouse employees, which they will then
use when picking items from the warehouse for an order delivery. The itemchoosing application requires the order manifest to be downloaded as XML.
You must modify the existing Transact-SQL query that generates the order
manifest so that it retrieves the data as XML.
Adventure Works is also creating a new ordering system for specific customers
so that they can send orders as XML documents. This system is still in the
initial testing phase. You must create the appropriate Transact-SQL required
to store the XML order details in the existing database tables.
You must also write Transact-SQL code for a delivery scheduling application
that retrieves information from the XML data and modifies the information by
using xml methods.

Lab Review
What is the xml Data Type?
What does the FOR XML clause do?
What is the purpose of XML Schemas?
What is an XML Schema Collection?
What Is XQuery?
What does the query() method do?
What are XML Indexes?

Module Review and Takeaways


Review Questions
Best Practices
Tools

Notes Page Over-flow Slide. Do Not Print Slide.


See Notes pane.

S-ar putea să vă placă și