Presentation is loading. Please wait.

Presentation is loading. Please wait.

Module 3: Using XML. Overview Retrieving XML by Using FOR XML Shredding XML by Using OPENXML Introducing XQuery Using the xml Data Type.

Similar presentations


Presentation on theme: "Module 3: Using XML. Overview Retrieving XML by Using FOR XML Shredding XML by Using OPENXML Introducing XQuery Using the xml Data Type."— Presentation transcript:

1 Module 3: Using XML

2 Overview Retrieving XML by Using FOR XML Shredding XML by Using OPENXML Introducing XQuery Using the xml Data Type

3 Lesson 1: 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 Practice: Using FOR XML

4 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 Client Application Database Server

5 ...... SELECT Cust.CustomerID CustID, CustomerType, SalesOrderID FROM Customer Cust JOIN SalesOrderHeader [Order] ON Cust.CustomerID = [Order].CustomerID ORDER BY Cust.CustomerID FOR XML RAW SELECT Cust.CustomerID CustID, CustomerType, SalesOrderID FROM Customer Cust JOIN SalesOrderHeader [Order] ON Cust.CustomerID = [Order].CustomerID ORDER BY Cust.CustomerID FOR XML RAW SELECT Cust.CustomerID CustID, CustomerType, SalesOrderID FROM Customer Cust JOIN SalesOrderHeader [Order] ON Cust.CustomerID = [Order].CustomerID ORDER BY Cust.CustomerID FOR XML RAW, ELEMENTS SELECT Cust.CustomerID CustID, CustomerType, SalesOrderID FROM Customer Cust JOIN SalesOrderHeader [Order] ON Cust.CustomerID = [Order].CustomerID ORDER BY Cust.CustomerID FOR XML RAW, ELEMENTS 1 S 43860... 1 S 43860... SELECT Cust.CustomerID CustID, CustomerType, SalesOrderID FROM Customer Cust JOIN SalesOrderHeader [Order] ON Cust.CustomerID = [Order].CustomerID ORDER BY Cust.CustomerID FOR XML RAW('Order'), ROOT('Orders') SELECT Cust.CustomerID CustID, CustomerType, SalesOrderID FROM Customer Cust JOIN SalesOrderHeader [Order] ON Cust.CustomerID = [Order].CustomerID ORDER BY Cust.CustomerID FOR XML RAW('Order'), ROOT('Orders') 1 S</...... 1 S</...... What Are RAW Mode Queries? XML representation of a rowset Contains either elements or attributes Optional root element and row element name

6 What Are AUTO Mode Queries? XML representation of data entities Nest data based on join precedence Can use options such as ELEMENTS and ROOT SELECT Cust.CustomerID CustID, CustomerType, SalesOrderID FROM Customer Cust JOIN SalesOrderHeader [Order] ON Cust.CustomerID = [Order].CustomerID ORDER BY Cust.CustomerID FOR XML AUTO SELECT Cust.CustomerID CustID, CustomerType, SalesOrderID FROM Customer Cust JOIN SalesOrderHeader [Order] ON Cust.CustomerID = [Order].CustomerID ORDER BY Cust.CustomerID FOR XML AUTO............

7 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 What Are EXPLICIT Mode Queries? 2001-07-01T00:00:00... 2001-07-01T00:00:00... Tabular representations of XML documents Allow complete control of XML format Element Attribute 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 2001-07-01T00:00:00... 2001-07-01T00:00:00... TagParentInvoice!1!InvoiceNoInvoice!1!Date!Element 1NULL436592001-07-01T00:00:00 1NULL436602001-07-02T00:00:00

8 What Are PATH Mode Queries? Use 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" FROMPerson.Contact INNER JOINEmployee ON Person.Contact.ContactID = Employee.ContactID FOR XML PATH SELECT EmployeeID "@EmpID", FirstName "EmpName/First", LastName "EmpName/Last" FROMPerson.Contact INNER JOINEmployee ON Person.Contact.ContactID = Employee.ContactID FOR XML PATH Guy Gilbert... Guy Gilbert...

9 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 Cust.CustomerID, CustomerType, SalesOrderID, Status FROM Customer Cust JOIN SalesOrderHeader [Order] ON Cust.CustomerID = [Order].CustomerID ORDER BY Cust.CustomerID FOR XML AUTO SELECT Cust.CustomerID, CustomerType, SalesOrderID, Status FROM Customer Cust JOIN SalesOrderHeader [Order] ON Cust.CustomerID = [Order].CustomerID ORDER BY Cust.CustomerID FOR XML AUTO SELECT Cust.CustomerID, CustomerType, SalesOrderID, Status FROM Customer Cust JOIN SalesOrderHeader [Order] ON Cust.CustomerID = [Order].CustomerID ORDER BY Cust.CustomerID FOR XML AUTO, ELEMENTS SELECT Cust.CustomerID, CustomerType, SalesOrderID, Status FROM Customer Cust JOIN SalesOrderHeader [Order] ON Cust.CustomerID = [Order].CustomerID ORDER BY Cust.CustomerID FOR XML AUTO, ELEMENTS 1 S 43860 5... 1 S 43860 5... SELECT Name CategoryName, (SELECT Name SubCategoryName FROM ProductSubCategory SubCategory WHERESubCategory.ProductCategoryID = Category.ProductCategoryID FOR XML AUTO, TYPE, ELEMENTS) FROM ProductCategory Category FOR XML AUTO SELECT Name CategoryName, (SELECT Name SubCategoryName FROM ProductSubCategory SubCategory WHERESubCategory.ProductCategoryID = Category.ProductCategoryID FOR XML AUTO, TYPE, ELEMENTS) FROM ProductCategory Category FOR XML AUTO Bike Racks... Bike Racks... 2001-07-01T00:00:00 Bike Socks, M Helmet, Blue... 2001-07-01T00:00:00 Bike Socks, M Helmet, Blue... SELECT 1 AS Tag, NULL AS Parent,... FROM SalesOrderHeader UNION ALL SELECT 2 AS Tag, 1 AS Parent,... FROM SalesOrderDetail OD JOIN... FOR XML EXPLICIT SELECT 1 AS Tag, NULL AS Parent,... FROM SalesOrderHeader UNION ALL SELECT 2 AS Tag, 1 AS Parent,... FROM SalesOrderDetail OD JOIN... FOR XML EXPLICIT

10 Practice: Using FOR XML In this practice, you will: Retrieve XML in RAW mode Retrieve XML in AUTO mode Retrieve XML in EXPLICIT mode Retrieve XML in PATH mode

11 Lesson 2: 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 Practice: Using OPENXML to Shred XML

12 XML document received from client 1 1 Overview of Shredding XML Data 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

13 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 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

14 OPENXML Syntax <Order SalesOrderID="43860" Status="5" OrderDate="2001-08-01T00:00:00"> <Order SalesOrderID="43860" Status="5" OrderDate="2001-08-01T00:00:00"> SELECT * FROM OPENXML (@idoc, '/Customer/Order/OrderDetail', 1) WITH (CustomerID int'../../@CustomerID', OrderID int'../@SalesOrderID', OrderDate datetime'../@OrderDate', ProdID int'@ProductID', Quantity int) SELECT * FROM OPENXML (@idoc, '/Customer/Order/OrderDetail', 1) WITH (CustomerID int'../../@CustomerID', OrderID int'../@SalesOrderID', OrderDate datetime'../@OrderDate', ProdID int'@ProductID', Quantity int) From Order element From Customer element Uses attributes as default rowpattern identifies node level Defaults to Quantity attribute From OrderDetail element

15 Syntax for Working With XML Namespaces sp_xml_preparedocument accepts namespaces Use namespace prefix in all XPath expressions <o:Order SalesOrderID="43860" Status="5" OrderDate="2001-08-01T00:00:00"> EXEC sp_xml_preparedocument @idoc OUTPUT, @doc, ' SELECT * FROM OPENXML (@idoc, '/rootNS:Customer/orderNS:Order/orderNS:OrderDetail') WITH... <o:Order SalesOrderID="43860" Status="5" OrderDate="2001-08-01T00:00:00"> EXEC sp_xml_preparedocument @idoc OUTPUT, @doc, ' SELECT * FROM OPENXML (@idoc, '/rootNS:Customer/orderNS:Order/orderNS:OrderDetail') WITH...

16 Practice: Using OPENXML to Shred XML In this practice, you will: Use the OPENXML function Shred XML by using elements only Shred XML by using attributes or elements Shred XML by using a colpattern parameter

17 Lesson 3: Introducing XQuery What Is XQuery? XQuery Basics XQuery Expressions

18 What Is XQuery? Query language to identify nodes in XML /InvoiceList/Invoice[@InvoiceNo=1000] FLWOR statements StatementDescription 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

19 Sequences and QNames XQuery Basics Result of an XQuery expression is a sequence All identifiers are 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 Arithmetic comparison General comparison Value comparison Node comparison Node order comparison Logical Comments (: Comment text :) if-then-else if ( $A eq $B ) then A else B if ( $A eq $B ) then A else B

20 Path expressions XQuery Expressions Relative Primary expressions Literals Variable references Function calls Literals Variable references Function calls Sequence expressions Construct, filter and combine sequences declare @x xml set @x = ' ' SELECT @x.query('/root/abc[attrAbc]') declare @x xml set @x = ' ' SELECT @x.query('/root/abc[attrAbc]') child::Address/child::Country Absolute /Address/Country

21 Lesson 4: Using the xml Data Type What Is the xml Data Type? The query, value, and exist Methods The modify Method The nodes Method Practice: Using the xml Data Type

22 What Is the xml Data Type? Native data type for XML Internal storage structure for XML InfoSet Use 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... -- 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...

23 The query, value, and exist Methods SELECT xmlCol.query( ' { for $i in /InvoiceList/Invoice return {number($i/@InvoiceNo)} } ') SELECT xmlCol.query( ' { for $i in /InvoiceList/Invoice return {number($i/@InvoiceNo)} } ') SELECT xmlCol.value( '(/InvoiceList/Invoice/@InvoiceNo)[1]', 'int') SELECT xmlCol.value( '(/InvoiceList/Invoice/@InvoiceNo)[1]', 'int') SELECT xmlCol.exist( '/InvoiceList/Invoice[@InvoiceNo=1000]' ) SELECT xmlCol.exist( '/InvoiceList/Invoice[@InvoiceNo=1000]' ) SELECT Invoices.query( ' {sql:column("StoreName")} ') SELECT Invoices.query( ' {sql:column("StoreName")} ') Use query to return untyped XML Use value to return a scalar value Bind relational columns and variables Use exist to check for the existence of a specified value

24 The modify Method SET @xmlDoc.modify( 'insert element salesperson {"Bill"} as first into (/InvoiceList/Invoice)[1]') SET @xmlDoc.modify( 'insert element salesperson {"Bill"} as first into (/InvoiceList/Invoice)[1]') SET xmlCol.modify( replace value of (/InvoiceList/Invoice/SalesPerson/text())[1] with "Ted"') SET xmlCol.modify( replace value of (/InvoiceList/Invoice/SalesPerson/text())[1] with "Ted"') SET @xmlDoc.modify( 'delete (/InvoiceList/Invoice/SalesPerson)[1]') SET @xmlDoc.modify( 'delete (/InvoiceList/Invoice/SalesPerson)[1]') insert adds child nodes or siblings to an XML document replace value of updates a node in the XML document delete removes a node from the XML document

25 The nodes Method SELECT nCol.value('@ProductID', 'int') Product, nCol.value('@Quantity', 'int') Qty FROM @xmlOrder.nodes('/Order/LineItem') AS nTable(nCol) SELECT nCol.value('@ProductID', 'int') Product, nCol.value('@Quantity', 'int') Qty FROM @xmlOrder.nodes('/Order/LineItem') AS nTable(nCol) SELECT nCol.value('../@OrderID[1]', 'int') ID, nCol.value('@ProductID[1]', 'int') Prod FROM Orders CROSS APPLY OrderDoc.nodes('/Order/LineItem') AS nTable(nCol) SELECT nCol.value('../@OrderID[1]', 'int') ID, nCol.value('@ProductID[1]', 'int') Prod FROM Orders CROSS APPLY OrderDoc.nodes('/Order/LineItem') AS nTable(nCol) Shreds xml variables into relational data Requires the APPLY operator with xml columns

26 Practice: Using the xml Data Type In this practice, you will: 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

27 Lab: Working With XML Exercise 1: Mapping Relational Data and XML Exercise 2: Storing XML Natively in the Database Exercise 3: Using XQuery With xml Methods


Download ppt "Module 3: Using XML. Overview Retrieving XML by Using FOR XML Shredding XML by Using OPENXML Introducing XQuery Using the xml Data Type."

Similar presentations


Ads by Google