Module 18 Querying XML Data in SQL Server® 2008 R2.

Slides:



Advertisements
Similar presentations
XML: Extensible Markup Language
Advertisements

Basic SQL Introduction Presented by: Madhuri Bhogadi.
Module 12: Auditing SQL Server Environments
Module 17 Tracing Access to SQL Server 2008 R2. Module Overview Capturing Activity using SQL Server Profiler Improving Performance with the Database Engine.
Module 6 Implementing Table Structures in SQL Server ®2008 R2.
Inside Data Access with SQLXML: Architecture Guide Rolandas Gricius MCT, MCSE, MCSD Adapted From.
1 COS 425: Database and Information Management Systems XML and information exchange.
Module 9 Designing an XML Strategy. Module 9: Designing an XML Strategy Designing XML Storage Designing a Data Conversion Strategy Designing an XML Query.
1 Advanced Topics XML and Databases. 2 XML u Overview u Structure of XML Data –XML Document Type Definition DTD –Namespaces –XML Schema u Query and Transformation.
SQL Server 2000 and XML Erik Veerman Consultant Intellinet Business Intelligence.
Viewing relational data as XML Using Microsoft SQL Server.
02 | Advanced SELECT Statements Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
DAT304 Leveraging XML and HTTP with Sql Server Irwin Dolobowsky Program Manager Webdata Group.
Module 17 Storing XML Data in SQL Server® 2008 R2.
2.2 SQL Server 2005 的 XML 支援功能. Overview XML Enhancements in SQL Server 2005 The xml Data Type Using XQuery.
Integrating XML with Microsoft SQL Server ©NIITeXtensible Markup Language/Lesson 9/Slide 1 of 31 Objectives In this lesson, you will learn to: * Generate.
XML, CFMX CFML & SQL XML Kevin Penny, MMCP
Using XML in SQL Server 2005 NameTitleCompany. XML Overview Business Opportunity The majority of all data transmitted electronically between organizations.
Module 12 Handling Errors in T-SQL Code. Module Overview Understanding T-SQL Error Handling Implementing T-SQL Error Handling Implementing Structured.
Module 8 Improving Performance through Nonclustered Indexes.
XML in SQL Server Overview XML is a key part of any modern data environment It can be used to transmit data in a platform, application neutral form.
Sofia, Bulgaria | 9-10 October Using XQuery to Query and Manipulate XML Data Stephen Forte CTO, Corzen Inc Microsoft Regional Director NY/NJ (USA) Stephen.
Module 7 Reading SQL Server® 2008 R2 Execution Plans.
Module 8: Implementing Stored Procedures. Introducing Stored Procedures Creating, Modifying, Dropping, and Executing Stored Procedures Using Parameters.
Module 9 Designing and Implementing Stored Procedures.
Graeme Malcolm | Senior Content Developer, Microsoft Geoff Allix | Principal Technologist, Content Master.
5/24/01 Leveraging SQL Server 2000 in ColdFusion Applications December 9, 2003 Chris Lomvardias SRA International
04 | Grouping and Aggregating Data Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
Objectives In this lesson, you will learn to: *Identify the need for ADO.NET *Identify the features of ADO.NET *Identify the components of the ADO.NET.
Module 4 Designing and Implementing Views. Module Overview Introduction to Views Creating and Managing Views Performance Considerations for Views.
SQL Basic. What is SQL? SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to communicate with a database.
Retrieving XML Data from SQL server.  Using the FOR XML Clause to Retrieve Data Retrieving Data in XML Format How SQL Server Generates XML Using the.
Module 3 Designing and Implementing Tables. Module Overview Designing Tables Working with Schemas Creating and Altering Tables.
Constraints cis 407 Types of Constraints & Naming Key Constraints Unique Constraints Check Constraints Default Constraints Misc Rules and Defaults Triggers.
06 | Modifying Data in SQL Server Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
XML and Database.
Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Module 11 Authorizing Users to Access Resources. Module Overview Authorizing User Access to Objects Authorizing Users to Execute Code Configuring Permissions.
Understanding Databases Lesson 6. Objective Domain Matrix Skills/ConceptsMTA Exam Objectives Understanding Relational Database Concepts Understand relational.
Chapter 14 1 Chapter 14 Storing and Retrieving XML in SQL Server 2000 November 6, 2001 Sook-Kyo Kwon.
Session 1 Module 1: Introduction to Data Integrity
05 | SET Operators, Windows Functions, and Grouping Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program.
SQLXML XML Technology For SQL Server Brian Moore Developer and Platform Strategy Group Microsoft Corporation.
Module 3: Using XML. Overview Retrieving XML by Using FOR XML Shredding XML by Using OPENXML Introducing XQuery Using the xml Data Type.
Module 10 Merging Data and Passing Tables. Module Overview Using the MERGE Statement Implementing Table Types Using Table Types As Parameters.
Module 9: Using Advanced Techniques. Considerations for Querying Data Working with Data Types Cursors and Set-Based Queries Dynamic SQL Maintaining Query.
Module 8: Using Programming Objects for Data Retrieval.
SQL SERVER.   Optionally, some other XML 
XML Extensible Markup Language
CSC314 DAY 8 Introduction to SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall SQL OVERVIEW  Structured Query Language  The.
SQL Triggers, Functions & Stored Procedures Programming Operations.
XML and SQL Server Better friends than you thought Matt Hartman.
Module 9: Implementing Functions. Overview Creating and Using Functions Working with Functions Controlling Execution Context.
1. Advanced SQL Functions Procedural Constructs Triggers.
Module 5: Working with Subqueries. Writing Basic Subqueries Writing Correlated Subqueries Comparing Subqueries with Joins and Temporary Tables Using Common.
Data Integrity & Indexes / Session 1/ 1 of 37 Session 1 Module 1: Introduction to Data Integrity Module 2: Introduction to Indexes.
XML: Extensible Markup Language
Using XML in SQL Server and Azure SQL Database
02 | Advanced SELECT Statements
Dirt, Spit, and Happy FLWOR
20761A 10: Using Subqueries Module 10   Using Subqueries.
Sorting and Filtering Data
Module 5: Implementing Data Integrity by Using Constraints
Overview Implementing Triggers Implementing XML Schemas.
Writing SELECT Queries
20761B 10: Using Subqueries Module 10   Using Subqueries.
Using Table Expressions
Database Processing: David M. Kroenke’s Chapter Seven:
Module 10: Implementing Managed Code in the Database
Contents Preface I Introduction Lesson Objectives I-2
Presentation transcript:

Module 18 Querying XML Data in SQL Server® 2008 R2

Module Overview Using the T-SQL FOR XML Statement Getting Started with XQuery Shredding XML

Lesson 1: Using the T-SQL FOR XML Statement Introducing the FOR XML clause Using RAW Mode Queries Using Auto Mode Queries Using Explicit Mode Queries Using Path Mode Queries Retrieving Nested XML Demonstration 1A: FOR XML Queries

Introducing the FOR XML clause Extends SELECT syntax Returns XML instead of rows and columns Is configurable to return attributes, elements, and schema Benefits client applications that work with XML Converted to XML Client Application Database Server

SELECT c.CustomerID AS CustID, soh.SalesOrderID FROM Sales.Customer AS c INNER JOIN Sales.SalesOrderHeader AS soh ON c.CustomerID = soh.CustomerID ORDER BY c.CustomerID FOR XML RAW; SELECT c.CustomerID AS CustID, soh.SalesOrderID FROM Sales.Customer AS c INNER JOIN Sales.SalesOrderHeader AS soh ON c.CustomerID = soh.CustomerID ORDER BY c.CustomerID FOR XML RAW; SELECT c.CustomerID AS CustID, soh.SalesOrderID FROM Sales.Customer AS c INNER JOIN Sales.SalesOrderHeader AS soh ON c.CustomerID = soh.CustomerID ORDER BY c.CustomerID FOR XML RAW, ELEMENTS; SELECT c.CustomerID AS CustID, soh.SalesOrderID FROM Sales.Customer AS c INNER JOIN Sales.SalesOrderHeader AS soh ON c.CustomerID = soh.CustomerID ORDER BY c.CustomerID FOR XML RAW, ELEMENTS; SELECT c.CustomerID AS CustID, soh.SalesOrderID FROM Sales.Customer AS c INNER JOIN Sales.SalesOrderHeader AS soh ON c.CustomerID = soh.CustomerID ORDER BY c.CustomerID FOR XML RAW('Order'), ROOT('Orders'); SELECT c.CustomerID AS CustID, soh.SalesOrderID FROM Sales.Customer AS c INNER JOIN Sales.SalesOrderHeader AS soh ON c.CustomerID = soh.CustomerID ORDER BY c.CustomerID FOR XML RAW('Order'), ROOT('Orders'); Using RAW Mode Queries … … Is an XML representation of a rowset Contains either elements or attributes Has optional root element and row element name … … … …

Using Auto Mode Queries SELECT Customer.CustomerID AS CustID, Customer.StoreID, [Order].SalesOrderID FROM Sales.Customer AS Customer INNER JOIN Sales.SalesOrderHeader AS [Order] ON Customer.CustomerID = [Order].CustomerID ORDER BY Customer.CustomerID FOR XML AUTO; SELECT Customer.CustomerID AS CustID, Customer.StoreID, [Order].SalesOrderID FROM Sales.Customer AS Customer INNER JOIN Sales.SalesOrderHeader AS [Order] ON Customer.CustomerID = [Order].CustomerID ORDER BY Customer.CustomerID FOR XML AUTO;

SELECT 1 AS Tag, NULL AS Parent, SalesOrderID AS [Invoice!1!InvoiceNo], OrderDate AS [Invoice!1!Date!Element] FROM SalesOrderHeader FOR XML EXPLICIT SELECT 1 AS Tag, NULL AS Parent, SalesOrderID AS [Invoice!1!InvoiceNo], OrderDate AS [Invoice!1!Date!Element] FROM SalesOrderHeader FOR XML EXPLICIT T00:00: T00:00:00... Using Explicit Mode Queries SELECT 1 AS Tag, NULL AS Parent, SalesOrderID AS [Invoice!1!InvoiceNo], OrderDate AS [Invoice!1!Date!Element] FROM Sales.SalesOrderHeader FOR XML EXPLICIT; SELECT 1 AS Tag, NULL AS Parent, SalesOrderID AS [Invoice!1!InvoiceNo], OrderDate AS [Invoice!1!Date!Element] FROM Sales.SalesOrderHeader FOR XML EXPLICIT; T00:00: T00:00:00 Allows tabular representation of XML documents TagParentInvoice!1!InvoiceNoInvoice!1!Date!Element 1NULL T00:00:00 1NULL T00:00:00 Attribute Element Allows complete control of XML format

Using Path Mode Queries SELECT p.BusinessEntityID p.FirstName "EmpName/First", p.LastName "EmpName/Last" FROM Person.Person AS p FOR XML PATH SELECT p.BusinessEntityID p.FirstName "EmpName/First", p.LastName "EmpName/Last" FROM Person.Person AS p FOR XML PATH Use XML Path Language (XPath) to specify XML format Allow creation of nested data and specify what should be exposed as an ELEMENT or an ATTRIBUTE Easier to use than EXPLICIT mode Min Su Min Su

SELECT Customer.CustomerID, Customer.TerritoryID, (SELECT SalesOrderID, [Status] FROM Sales.SalesOrderHeader AS soh WHERE Customer.CustomerID = soh.CustomerID FOR XML AUTO, TYPE) as Orders FROM Sales.Customer as Customer ORDER BY Customer.CustomerID FOR XML AUTO, ELEMENTS; SELECT Customer.CustomerID, Customer.TerritoryID, (SELECT SalesOrderID, [Status] FROM Sales.SalesOrderHeader AS soh WHERE Customer.CustomerID = soh.CustomerID FOR XML AUTO, TYPE) as Orders FROM Sales.Customer as Customer ORDER BY Customer.CustomerID FOR XML AUTO, ELEMENTS; SELECT Cust.CustomerID, Cust.StoreID, [Order].SalesOrderID, [Order].[Status] FROM Sales.Customer AS Cust INNER JOIN Sales.SalesOrderHeader AS [Order] ON Cust.CustomerID = [Order].CustomerID ORDER BY Cust.CustomerID FOR XML AUTO, ELEMENTS; SELECT Cust.CustomerID, Cust.StoreID, [Order].SalesOrderID, [Order].[Status] FROM Sales.Customer AS Cust INNER JOIN Sales.SalesOrderHeader AS [Order] ON Cust.CustomerID = [Order].CustomerID ORDER BY Cust.CustomerID FOR XML AUTO, ELEMENTS; SELECT Cust.CustomerID, Cust.StoreID, SalesOrderID, [Status] FROM Sales.Customer AS Cust INNER JOIN Sales.SalesOrderHeader AS [Order] ON Cust.CustomerID = [Order].CustomerID ORDER BY Cust.CustomerID FOR XML AUTO; SELECT Cust.CustomerID, Cust.StoreID, SalesOrderID, [Status] FROM Sales.Customer AS Cust INNER JOIN Sales.SalesOrderHeader AS [Order] ON Cust.CustomerID = [Order].CustomerID ORDER BY Cust.CustomerID FOR XML AUTO; AUTO mode produces only attributes or elements AUTO mode produces only attributes Retrieving Nested XML Use inner FOR XML with TYPE clause to return xml data type

Demonstration 1A: FOR XML Queries In this demonstration, you will see: How to retrieve XML in RAW mode How to retrieve XML in AUTO mode How to retrieve XML in EXPLICIT mode How to retrieve XML in PATH mode How to use TYPE

Lesson 2: Getting Started with XQuery What is XQuery? query() Method value() Method exist() Method modify() Method Demonstration 2A: XQuery Methods in a DDL Trigger

What is XQuery? Can query structured or semi-structured XML FLWOR expressions StatementDescription forIterate through sibling nodes whereApply filtering criteria to the iteration order bySort values in returned resultset returnSpecify the XML to be returned Query language to identify nodes in XML

query() Method Returns untyped XML Uses an XQuery expression SELECT XmlEvent.query( ' { for $e in /EVENT_INSTANCE return {number($e/SPID[1])} } ') FROM dbo.DatabaseLog; SELECT XmlEvent.query( ' { for $e in /EVENT_INSTANCE return {number($e/SPID[1])} } ') FROM dbo.DatabaseLog;

value() Method Extracts scalar values from XML documents Returns data as a relational column SELECT CatalogDescription.value(' declare namespace PD=" dventure-works/ProductModelDescription"; ', 'int') as Result FROM Production.ProductModel WHERE CatalogDescription IS NOT NULL ORDER BY ProductModelID; SELECT CatalogDescription.value(' declare namespace PD=" dventure-works/ProductModelDescription"; ', 'int') as Result FROM Production.ProductModel WHERE CatalogDescription IS NOT NULL ORDER BY ProductModelID;

exist() Method Checks for the existence of a specific value Returns 1 when the value exists, 0 when it does not Should be used in preference to value() for better performance SELECT * FROM dbo.DatabaseLog WHERE XmlEvent.exist ('/EVENT_INSTANCE[ObjectType="TABLE"]') = 1; SELECT * FROM dbo.DatabaseLog WHERE XmlEvent.exist ('/EVENT_INSTANCE[ObjectType="TABLE"]') = 1;

'replace value of (/InvoiceList/Invoice/SalesPerson/text())[1] with "Ted"'); 'replace value of (/InvoiceList/Invoice/SalesPerson/text())[1] with "Ted"'); 'delete (/InvoiceList/Invoice/SalesPerson)[1]'); 'delete (/InvoiceList/Invoice/SalesPerson)[1]'); modify() Method 'insert element salesperson {"Bill"} as first into (/InvoiceList/Invoice)[1]'); 'insert element salesperson {"Bill"} as first into (/InvoiceList/Invoice)[1]'); “insert” adds child nodes to an XML document “replace value of” updates node in an XML document “delete” removes a node from the XML document

Demonstration 2A: XQuery Methods in a DDL Trigger In this demonstration, you will see how to use XQuery in DDL triggers

Lesson 3: Shredding XML Overview of Shredding XML data Stored Procedures for Managing In-Memory Node Trees OPENXML Working with XML Namespaces nodes() Method Demonstration 3A: Shredding XML

Overview of Shredding XML data XML document received from client 1 1 Use OPENXML to retrieve rowset 3 3 Use sp_xml_removedocument to clean up memory tree 5 5 Create internal tree representation by using sp_xml_preparedocument Create internal tree representation by using sp_xml_preparedocument 2 2 Process (or shred) the data into tables 4 4

Stored Procedures for Managing In-Memory Node Trees CREATE PROCEDURE xml AS -- Declare document handle int; -- Create memory tree EXEC -- Code for processing document goes here -- using OPENXML -- Remove memory tree EXEC CREATE PROCEDURE xml AS -- Declare document handle int; -- Create memory tree EXEC -- Code for processing document goes here -- using OPENXML -- Remove memory tree EXEC Create tree by using sp_xml_preparedocument Free memory by using sp_xml_removedocument

OPENXML <Order SalesOrderID="43860" Status="5" OrderDate=" T00:00:00"> <Order SalesOrderID="43860" Status="5" OrderDate=" T00:00:00"> SELECT * FROM OPENXML '/Customer/Order/OrderDetail', 1) WITH (CustomerID OrderID OrderDate ProdID Quantity int) SELECT * FROM OPENXML '/Customer/Order/OrderDetail', 1) WITH (CustomerID OrderID OrderDate ProdID Quantity int) From Order element From Customer element Uses attributes as default rowpattern identifies node level Defaults to Quantity attribute From OrderDetail element ColPattern identifies SalesOrderID, Status, and OrderDate

Working with XML Namespaces <Customer xmlns="urn:AW_NS" xmlns:o="urn:AW_OrderNS" CustomerID="1" CustomerType="S"> <o:Order SalesOrderID="43860" Status="5" OrderDate=" T00:00:00"> <Customer xmlns="urn:AW_NS" xmlns:o="urn:AW_OrderNS" CustomerID="1" CustomerType="S"> <o:Order SalesOrderID="43860" Status="5" OrderDate=" T00:00:00"> sp_xml_preparedocument accepts namespaces Use namespace prefix in all XPath expressions EXEC '<ROOT xmlns:rootNS="urn:AW_NS" xmlns:orderNS="urn:AW_OrderNS"/>'; SELECT * FROM OPENXML '/rootNS:Customer/orderNS:Order/orderNS:OrderDetail')... EXEC '<ROOT xmlns:rootNS="urn:AW_NS" xmlns:orderNS="urn:AW_OrderNS"/>'; SELECT * FROM OPENXML '/rootNS:Customer/orderNS:Order/orderNS:OrderDetail')...

nodes() Method SELECT 'int') Product, 'int') Qty AS nTable(nCol) SELECT 'int') Product, 'int') Qty AS nTable(nCol) SELECT EventDetail.value('PostTime[1]','datetime2') AS PostTime, EventDetail.value('SPID[1]', 'int') AS SPID, EventDetail.value('ObjectType[1]','sysname') AS ObjectType, EventDetail.value('ObjectName[1]','sysname') AS ObjectName FROM dbo.DatabaseLog AS dl CROSS APPLY dl.XmlEvent.nodes('/EVENT_INSTANCE') AS EventInfo(EventDetail) ORDER BY PostTime; SELECT EventDetail.value('PostTime[1]','datetime2') AS PostTime, EventDetail.value('SPID[1]', 'int') AS SPID, EventDetail.value('ObjectType[1]','sysname') AS ObjectType, EventDetail.value('ObjectName[1]','sysname') AS ObjectName FROM dbo.DatabaseLog AS dl CROSS APPLY dl.XmlEvent.nodes('/EVENT_INSTANCE') AS EventInfo(EventDetail) ORDER BY PostTime; Shreds XML variables into relational data Requires the APPLY operator with XML columns

Demonstration 3A: Shredding XML In this demonstration, you will see how to shred XML data using the nodes() method

Lab 18: Querying XML Data in SQL Server Exercise 1: Learn to query SQL Server data as XML Exercise 2: Write a stored procedure returning XML Challenge Exercise 3: Write a stored procedure that updates using XML (Only if time permits) Logon information Estimated time: 45 minutes

Lab Scenario In this lab, you will investigate several ways in which XML data can be used in SQL Server. You will query relational data and return it as XML and also process existing XML data using T-SQL. If you have time, your manager has an additional task for you. A new web service is being added to the marketing system. You need to create a stored procedure that will query data from a table and return it as an XML value.

Lab Review XML data could be passed to a stored procedure using either the XML data type or the nvarchar data type. What advantage does the XML data type provide over the nvarchar data type for this purpose? Which XML query mode did you use for implementing the WebStock.GetAvailableModelsAsXML stored procedure?

Module Review and Takeaways Review Questions Best Practices