0% found this document useful (0 votes)
59 views46 pages

Storing and Querying XML Data in SQL Server

This document provides an overview of Module 14 which covers storing and querying XML data in SQL Server. It includes 6 lessons that cover topics such as introducing XML and XML schemas, storing XML data and schemas in SQL Server, implementing the XML data type, using the FOR XML statement, getting started with XQuery, and shredding XML. Each lesson includes demonstrations of the concepts and techniques covered.

Uploaded by

Vlada Grujić
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views46 pages

Storing and Querying XML Data in SQL Server

This document provides an overview of Module 14 which covers storing and querying XML data in SQL Server. It includes 6 lessons that cover topics such as introducing XML and XML schemas, storing XML data and schemas in SQL Server, implementing the XML data type, using the FOR XML statement, getting started with XQuery, and shredding XML. Each lesson includes demonstrations of the concepts and techniques covered.

Uploaded by

Vlada Grujić
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Module 14

Storing and Querying XML Data in


SQL Server
Module Overview

Introduction to XML and XML Schemas


Storing XML Data and Schemas in SQL Server
Implementing the XML Data Type
Using the Transact-SQL FOR XML Statement
Getting Started with XQuery
• Shredding XML
Lesson 1: Introduction to XML and XML Schemas

Core XML Concepts


Fragments vs. Documents
XML Namespaces
XML Schemas
Appropriate Use of XML Data Storage in SQL Server
• Demonstration: Introduction to XML and XML
Schemas
Core XML Concepts

• XML is a plain-text, Unicode-based


metalanguage
• It represents both structured and semistructured
data
• It is not tied to any programming language,
operating system, or vendor
• There are two approaches to encoding XML:
• Element-centric
• Attribute-centric
Fragments vs. Documents

• XML Document
• One top-level root element

• XML Fragment
• Multiple top-level elements
• Well-formed XML will include at least a prolog,
one top-level element, and correctly nested
element tags
XML Namespaces

• Primarily used to avoid element name conflicts


• One XML document can have many namespace
definitions associated with it
• Namespaces are commonly attached to prefixes;
if defined without a prefix, the namespace
becomes the default for the XML document
• Defined as an XML attribute:
• xmlns:URL
XML Schemas

• XML schema describes the structure of an XML


document
• XML schema language is also called XML Schema
Definition (XSD)
• An XML schema provides for the following:
• Ability to validate constraints
• Validation of the data by SQL Server
• Data type information
• Information about types of attributes and elements, the
permitted structure of the XML
Appropriate Use of XML Data Storage in SQL
Server

• Use Cases
• Processing XML from external applications
• Structure of the data is undefined
• Improve the interoperability of the data
• An explicit sequence within the data needs to be
maintained
• Indexing and improved querying is required on the
XML
Demonstration: Introduction to XML and XML
Schemas

In this demonstration, you will see how to:


• Structure XML and structure XML schemas
Lesson 2: Storing XML Data and Schemas in SQL
Server

XML Data
XML Schema Collections
Untyped vs. Typed XML
CONTENT vs. DOCUMENT
• Demonstration: Working with Typed vs. Untyped
XML
XML Data

• SQL Server has a native data type for XML


• Enables you to store XML documents and
fragments
• Can be used for columns, variables, or
parameters
• Can be indexed
• Exposes methods to query and modify XML
• XML is stored efficiently in an internal format and
returned in its canonical form
XML Schema Collections

• You can associate XSD schemas with an xml data


type through an XML schema collection
• The XML schema collection:
• Stores the imported XML schemas
• Validates XML instances
• Types the XML data as it is stored in the database

• When an XSD is associated with XML it is said to


be typed
Untyped vs. Typed XML

• Use the untyped XML data type in the following


situations:
• You do not have a schema for your XML data
• You have schemas, but don’t want the server to
validate the data
• Use the typed XML data type in the following
situations:
• You have schemas and want the server to validate XML
data
• You want to take advantage of storage and query
optimizations based on type information
• You want to take advantage of type information during
compilation of your queries
CONTENT vs. DOCUMENT

• CONTENT is the default value


• If nothing is specified, SQL Server will allow XML
fragments to be stored
• DOCUMENT can be specified for typed XML
• If an xml column has been linked to an XML Schema
Collection, it can be defined as only allowing well-
formed documents
Demonstration: Working with Typed vs. Untyped
XML

In this demonstration, you will see how to:


• Work with typed and untyped XML
Lesson 3: Implementing the XML Data Type

What Are XML Indexes?


Types of XML Indexes
• Demonstration: Implementing XML Indexes
What Are XML Indexes?

• XML data can be slow to access


• XML indexes can help with query performance
Types of XML Indexes

Primary XML index


• Provides a persisted object tree in an internal format
that is used to speed access to elements and attributes
within the XML
• Requires a clustered primary key on the table

Secondary XML index


• Can only be constructed after a primary XML index has
been created
• You can construct three types of secondary indexes to
help answer specific XQuery queries rapidly:
• PATH
• PROPERTY
• VALUE
Demonstration: Implementing XML Indexes

In this demonstration, you will see how to


implement XML indexes
Lesson 4: Using the Transact-SQL FOR XML
Statement

Introduction to the FOR XML Clause


Using RAW Mode Queries
Using Auto Mode Queries
Using Explicit Mode Queries
Using Path Mode Queries
Retrieving Nested XML
• Demonstration: FOR XML Queries
Introduction to the FOR XML Clause

• Extends Transact-SQL SELECT syntax


• Returns data as XML instead of rows and
columns
• Is configurable to return attributes, elements, and
the schema
• Has four different modes:
• RAW
• AUTO
• EXPLICIT
• PATH
Using RAW Mode Queries

• Enables SQL Server to return data as XML


• Can produce element- or attribute-centric XML
• Default is to produce XML fragments
• Does not include NULL columns
• Has additional options to:
• Add a root node
• Rename elements
• Generate an XML schema
• Include NULL data with the XSINIL option
Using Auto Mode Queries

• Enables SQL Server to return data as nested XML


elements
• Can produce element- or attribute-centric XML
• Default is to produce XML fragments
• Does not include NULL columns
• Has the same additional options as RAW mode:
• Add a root node
• Rename elements by using aliases
• Generate an XML schema
• Include NULL data with the XSINIL option
Using Explicit Mode Queries

• Explicit mode
• Enables tabular representation of XML documents
• Enables complete control of the XML format
• Requires complex SQL statements that can be more
easily generated with other modes
Using Path Mode Queries

• Uses XML Path Language (X Path) to specify XML


format
• Enables the creation of nested data and specifies
what should be exposed as an element or an
attribute
• Column aliases determine the output:
• @, the column will be added as an attribute
• / will describe the hierarchy of the element
• The two can be combined

• Easier to use than EXPLICIT mode


Retrieving Nested XML

• Nested FOR XML statements with a TYPE option


will create data in xml format
• If TYPE isn’t used, the data is returned as
characters
• You can nest FOR XML statements inside other
FOR XML statements to create complex XML
structures
• TYPE can be used on all modes of the FOR XML
statement
Demonstration: FOR XML Queries

In this demonstration, you will see how to use FOR


XML queries
Lesson 5: Getting Started with XQuery

What is XQuery?
The query() Method
The value() Method
The exist() Method
The modify() Method
• Demonstration: XQuery Methods in a DDL Trigger
What is XQuery?

• A querying language for XML


• Includes other language elements, for example
looping
• Supports FLWOR
• For, Let, Where, Order, and Return
• Has five methods
• query(), value(), exist(), modify(), and nodes()
The query() Method

• Returns untyped XML


• Expects a valid XQuery as input
• Can include the FLWOR statements
• Example:
• SELECT Demographics.query
('StoreSurvev/NumberEmplovees')
FROM Sales.Store;
The value() Method

• Returns the specified SQL type


• Returns the data as a relational column
• There are some SQL types that can't be returned:
• xml data type, (CLR) user-defined type, image, text,
ntext, or sql_variant
• Example:
SELECT Demographics.value(
'(/StoreSurvey/NumberEmployees[1]’int’)
AS Staff
FROM sales.store;
The exist() Method

• Checks for the existence of a specific value


• Should be used in preference of a value() method
for better performance
• Returns three possible values:
• 1, indicates that the value was found
• 0, indicates that the value wasn't found
• NULL, indicates the XML being inspected in NULL

• Example:
SELECT BusinessEntitylD
FROM Sales.Store
WHERE Demographics.exist(
‘/StoreSurvey[NumberEmployees=14]’
The modify() Method

• The modify() method:


• Modifies the contents of XML, in either an XML variable
or column
• Depending on the options selected, modify can:
• Insert a new XML element—via insert command
• Update the contents on an existing element—via the
replace value of command
• Delete an XML element—via delete command

• If updating an XML column, the modify() method


has to be used in an UPDATE statement
Demonstration: XQuery Methods in a DDL
Trigger

In this demonstration, you will see how to use


XQuery in DDL triggers
Lesson 6: Shredding XML

Overview of Shredding XML Data


Stored Procedures for Managing In-Memory Node
Trees
OPENXML Function
Working with XML Namespaces
nodes() Method
• Demonstration: Shredding XML
Overview of Shredding XML Data

• There are two approaches to shredding XML


• Using OPENXML and associated stored procedures
• Using the xml nodes() method

• In most situations, nodes() method will perform


better than OPENXML
Stored Procedures for Managing In-Memory
Node Trees

• Create an in-memory node tree by using


sp_xml_preparedocument
• Uses the Microsoft XML Core Services
• Delete the created node tree and free the
memory by using sp_xml_removedocument
OPENXML Function

• Provides a rowset over in-memory XML


documents
• Can be used to shred XML but also produce an
edge table
• Example:

SELECT * FROM OPENXML(@xmldoc,


'/ns:Resume/ns:Employment', 2)
WITH (
StartDate DATETIME 'ns:Emp.StartDate'
, EndDate DATETIME 'ns:Emp.EndDate'
, OrgName NVARCHAR(1000) 'ns:Emp.OrgName'
)
Working with XML Namespaces

• sp_xml_preparedocument accepts namespaces as


the last parameter
• Use namespace prefix in all XPath expressions
• Namespaces can be used with FOR XML
statements and xml data methods with a WHERE
clause
nodes() Method

• Shreds XML variables into relational data


• Requires the APPLY operator with XML columns
• Example:

SELECT person.BusinessEntityID,
person.LastName,
contact.value('act:number','nvarchar(4000)') As
ChangeInContactNumber
FROM Person.Person AS person
CROSS APPLY person.AdditionalContactInfo.nodes(
'/AdditionalContactInfo/act:telephoneNumber‘
) AS helpdesk(contact)
WHERE person.AdditionalContactInfo IS NOT NULL;
Demonstration: Shredding XML

In this demonstration, you will see how to:


• Shred XML data by using the nodes() method
• Shred XML using the OPENXML method
Lab: Storing and Querying XML Data in SQL
Server

Exercise 1: Determining When to Use XML


Exercise 2: Testing XML Data Storage in Variables
Exercise 3: Using XML Schemas
Exercise 4: Using FOR XML Queries
• Exercise 5: Creating a Stored Procedure to Return
XML
Logon Information
Virtual machine: 20762C-MIA-SQL
User name: ADVENTUREWORKS\Student
Password: Pa55w.rd

Estimated Time: 45 minutes


Lab Scenario

A new developer in your organization has


discovered that SQL Server can store XML directly.
He is keen to use this mechanism extensively. In
this lab, you will decide on the appropriate usage
of XML in the documented application.
You also have an upcoming project that will
require the use of XML data in SQL Server. No
members of your current team have experience
working with XML data in SQL Server.
Lab Scenario (Continued)

You need to learn how to process XML data within


SQL Server and you have been given some sample
queries to assist with this learning. Finally, you will
use what you have learned to write a stored
procedure for the marketing system that returns
XML data.
Lab Review

• In this lab, you decided when it is appropriate to


use XML data in SQL Server in different situations.
Module Review and Takeaways

Review Question(s)
• Best Practice

You might also like