Module 3 Lab: Working With XML: Exercise 1: Mapping Relational Data and XML

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Module 3 Lab: Working with XML

Exercise 1: Mapping Relational Data and XML

Lab answer key

Creating FOR XML queries to return the order manifest documents


You must perform the following steps to create FOR XML queries to return the order
manifest documents:

1. Click Start, point to All Programs, point to Microsoft SQL Server 2005, and then click
SQL Server Management Studio.
2. In the Connect to Server dialog box, specify the values in the following table, and then click
Connect.
Property Value
Server type Database Engine
Server name MIAMI
Authentication Windows Authentication

3. On the File menu, point to Open, click Project/Solution, and then click the XML.ssmssln
solution in D:\Labfiles\Starter.
4. If Solution Explorer is not visible, click Solution Explorer on the View menu.
5. In Solution Explorer, double-click the FORXML.sql query.
6. Examine the query, noting that it retrieves data from the Sales.SalesOrderHeader and
Sales.SalesOrderDetail tables in the AdventureWorks database.
7. On the toolbar, click Execute, and then review the query results.
8. Modify the SELECT statement to include the FOR XML clause and return attribute-centric
XML by using AUTO mode, as shown in the following Transact-SQL example.

SELECT SalesOrder.SalesOrderID,
SalesOrder.OrderDate,
SalesOrder.AccountNumber,
Item.ProductID,
Item.OrderQty
FROM Sales.SalesOrderHeader SalesOrder
JOIN Sales.SalesOrderDetail Item
ON SalesOrder.SalesOrderID = Item.SalesOrderID
WHERE SalesOrder.SalesOrderID = 43659
FOR XML AUTO
9. On the toolbar, click Execute, and review the query results, verifying that they return the
required XML format, as shown in the following sample output.

<SalesOrder SalesOrderID="43659" OrderDate="2001-07-01T00:00:00"


AccountNumber="10-4020-000676">
<Item ProductID="776" OrderQty="1" />
<Item ProductID="777" OrderQty="3" />
<Item ProductID="778" OrderQty="1" />
<Item ProductID="771" OrderQty="1" />
<!-- more items here -->
</SalesOrder>

10. Select the SELECT statement, and on the Edit menu, click Copy. Position the insertion point
below the existing SELECT statement, and on the Edit menu, click Paste.
11. Modify the new SELECT statement to include an inner SELECT query that returns XML data
by using the FOR XML clause combined with the AUTO mode, ELEMENTS directive, and
TYPE directive, as shown in the following Transact-SQL example.

SELECT SalesOrder.SalesOrderID,
SalesOrder.OrderDate,
SalesOrder.AccountNumber,
(SELECT Item.ProductID, Item.OrderQty
FROM Sales.SalesOrderDetail Item
WHERE SalesOrder.SalesOrderID = Item.SalesOrderID
FOR XML AUTO, ELEMENTS, TYPE)
FROM Sales.SalesOrderHeader SalesOrder
WHERE SalesOrder.SalesOrderID = 43659
FOR XML AUTO

12. Select the new SELECT statement, and on the toolbar, click Execute. In the query results,
click the returned XML to view it in the XML Editor, and then verify that the query returned
the required XML format, as shown in the following sample output. Then close the XML
Editor window.

<SalesOrder SalesOrderID="43659" OrderDate="2001-07-01T00:00:00"


AccountNumber="10-4020-000676">
<Item>
<ProductID>776</ProductID>
<OrderQty>1</OrderQty>
</Item>
<Item>
<ProductID>777</ProductID>
<OrderQty>3</OrderQty>
</Item>
<Item>
<ProductID>778</ProductID>
<OrderQty>1</OrderQty>
</Item>
<Item>
<!-- more items here -->
</SalesOrder>
13. On the File menu, click Save FORXML.sql.
14. Keep the SQL Server Management Studio solution open. You will use it in the next part of
this exercise.

Using the OPENXML function to insert the XML data into the tables
You must perform the following steps to use the OPENXML function to insert the XML
data into the tables:

1. In Solution Explorer, double-click OPENXML.sql.


2. Examine the query in the file, noting that it provides a sample XML document that contains a
sales order from a customer for two items. The remainder of the file is incomplete.
3. Locate the comment Call stored procedure to create the memory tree, and then add a call
to the sp_xml_preparedocument stored procedure, as shown in the following example.

EXEC sp_xml_preparedocument @docHandle OUTPUT, @doc

4. Locate the comment Add OPENXML statement for SalesOrderHeader table INSERT,
and then add an OPENXML function to retrieve the relevant attributes from the SalesOrder
node, as shown in the following example.

OPENXML(@docHandle, '/SalesOrder', 1)
WITH
( CustomerID int,
DueDate datetime,
AccountNumber nvarchar(15),
ContactID int,
BillToAddressID int,
ShipToAddressID int,
ShipMethodID int,
SubTotal money,
TaxAmt money)

5. Locate the comment Add OPENXML statement for SalesOrderDetail table INSERT, and
then add an OPENXML function to retrieve the relevant subelements from the Item node, as
shown in the following example.

OPENXML(@docHandle, '/SalesOrder/Item', 2)
WITH
( OrderQty int,
ProductID int,
UnitPrice money)

6. Locate the comment Call stored procedure to clean up memory tree, and then add a call to
the sp_xml_removedocument stored procedure, as shown in the following example.

EXEC sp_xml_removedocument @docHandle

7. On the toolbar, click Execute.


8. Review the results, and confirm that a new record was added to the SalesOrderHeader table
and two records were added to the SalesOrderDetail table.
9. On the File menu, click Save OPENXML.sql.
10. Keep the SQL Server Management Studio solution open. You will use it in the next exercise.
Exercise 2: Storing XML Natively in the Database

Lab answer key

Creating the Sales.DeliverySchedule table and inserting test data


You must perform the following steps to create the Sales.DeliverySchedule table and
insert test data:

1. On the Project menu, click New Query. When prompted, use Windows authentication to
connect to MIAMI.
2. If Solution Explorer is not visible, click Solution Explorer on the View menu.
3. In Solution Explorer, right-click SQLQuery1.sql, and then click Rename. Rename the file
xmlDataType.sql.
4. Type the following Transact-SQL code to create a table named Sales.DeliverySchedule in
the AdventureWorks database.
USE AdventureWorks
GO
CREATE TABLE Sales.DeliverySchedule
(ScheduleID int IDENTITY PRIMARY KEY,
ScheduleDate DateTime,
DeliveryRoute int,
DeliveryDriver nvarchar(20),
DeliveryList xml)

5. Select the CREATE TABLE statement, and then on the toolbar, click Execute. Verify that
the command completes successfully.
6. In the Miscellaneous folder in Solution Explorer, double-click DeliveryList.xml, and then
examine its contents. This is an XML delivery list document.
7. Switch back to the xmlDataType.sql query window, and then type the following Transact-
SQL code.
INSERT INTO Sales.DeliverySchedule
VALUES
(GetDate(), 3, 'Alice', '<?xml version="1.0" ?>
<DeliveryList>
<Delivery SalesOrderID="43659">
<CustomerName>Steve Schmidt</CustomerName>
<Address>6126 North Sixth Street,
Rockhampton</Address>
</Delivery>
<Delivery SalesOrderID="43660">
<CustomerName>Tony Lopez</CustomerName>
<Address>6445 Cashew Street,
Rockhampton</Address>
</Delivery>
</DeliveryList>')
You can copy the XML document in DeliveryList.xml and paste it into the query editor.
8. Select your code, and then on the toolbar, click Execute.
9. Verify that the data has been entered by executing the following Transact-SQL SELECT
statement.

SELECT * FROM Sales.DeliverySchedule

Using xml data methods to query and modify the data


You must perform the following steps to use xml data methods to query and modify the
data:

1. On the Project menu, click New Query. When prompted, use Windows authentication to
connect to MIAMI.
2. If Solution Explorer is not visible, click Solution Explorer on the View menu.
3. In Solution Explorer, right-click SQLQuery1.sql, and then click Rename. Rename the file
xmlMethods.sql.
4. Type the following Transact-SQL.

USE AdventureWorks
SELECT DeliveryDriver,
DeliveryList.query('/DeliveryList/Delivery') As Deliveries
FROM Sales.DeliverySchedule

5. Select your code, and then on the toolbar, click the Execute button.
6. Verify that the desired results are returned.
7. Type the following Transact-SQL to retrieve a single nvarchar(100) column named
DeliveryAddress containing the address for the first delivery in the delivery list document for
the record in the Sales.DeliverySchedule table with a ScheduleID of 1.

SELECT DeliveryList.value(
'(/DeliveryList/Delivery/Address)[1]', 'nvarchar(100)')
As DeliveryAddress
FROM Sales.DeliverySchedule
WHERE ScheduleID = 1

8. Select your code, and then on the toolbar, click the Execute button.
9. Verify that the desired results are returned.
10. Type the following Transact-SQL to retrieve the DeliveryDriver column in the
Sales.DeliverySchedule table, where the XML in the DeliveryList column includes a
Delivery element with a SalesOrderID attribute of 43659.

SELECT DeliveryDriver
FROM Sales.DeliverySchedule
WHERE DeliveryList.exist('/DeliveryList/Delivery[@SalesOrderID=43659]')
= 1
11. Select your code, and then on the toolbar, click the Execute button.
12. Verify that the desired results are returned.
13. Type the following Transact-SQL to retrieve a delivery route document in the required XML
format from the DeliveryList column in each row of the Sales.DeliverySchedule table.

SELECT DeliveryList.query
('<DeliveryRoute>
<RouteNo>{sql:column("DeliveryRoute")}</RouteNo>
{
for $d in /DeliveryList/Delivery
return $d/Address
}
</DeliveryRoute>')
FROM Sales.DeliverySchedule
14. Select your code, and then on the toolbar, click the Execute button.
15. Verify that the desired results are returned.
16. Type the following Transact-SQL to update the Sales.DeliverySchedule table, setting the
first Address element value in the delivery list document for the record with a ScheduleID of
1 to 7194 Fourth St. Rockhampton.

UPDATE Sales.DeliverySchedule
SET DeliveryList.modify('replace value of
(/DeliveryList/Delivery/Address/text())[1]
with "7194 Fourth St. Rockhampton"')
WHERE ScheduleID = 1
17. Select your code, and then on the toolbar, click the Execute button.
18. Verify that the operation was successful by executing the following Transact-SQL statement.

SELECT DeliveryList.value('
(/DeliveryList/Delivery/Address)[1]', 'nvarchar(100)')
FROM Sales.DeliverySchedule
WHERE ScheduleID = 1
19. On the File menu, click Save All, and then close SQL Server Management Studio.

You might also like