Practical SQL: DB2 at Home, Part 5, Building Tables with XML

SQL
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

XML is great for hierarchical data, but sometimes you still need a plain old table, and this article will show you how to build one.

 

Last time, we took a little segue into creating XML from relational data. Now it's time to return to the other direction, making relational tables from XML data. XML can easily support a complex nested relationship of data with both optional and repeating elements, but that doesn't always translate very well to the relational world in which the data is presented as nice tables of rows and columns. In this article, I'll introduce you to the techniques you can use to turn hierarchies into grids.

 

XML Versus RelationalA Story of Structure

The real thing I've been trying to do in all of these articles is to compare how data is stored in XML as opposed to our more traditional relational data approach, and how to exploit the differences by building on the similarities. The subject of this article is the XMLTable function, which in a lot of ways really defines how these two data storage techniques equate to one another.

 

Let's start by taking a look at a standard XML structure. Like all the data in these articles, the data comes from the DB2 appliance that we installed way back at the beginning of the series. You could certainly create your own, but it's nice to have common ground to start from. In this case, the common ground is a purchase order, the XML for which looks like this:

 

<PurchaseOrder

PoNum="5003"

OrderDate="2005-02-28"

Status="UnShipped">

<item>

   <partid>100-100-01</partid>

   <name>Snow Shovel, Basic 22 inch</name>

   <quantity>1</quantity>

   <price>9.99</price>

</item>

</PurchaseOrder>

 

This data resides in a column named PORDER in the table PURCHASEORDER. Yes, I know it's not a traditional 10-character file name, but SQL support on the IBM i allows you to easily get around the constraints for both file and field name. Of course, that means that sometimes people go crazy and create fields like ThirdQuarterInvoiceSubtotalForTemporaryTaxCalculations, but that's a different issue. Anyway, the files and fields are already defined in the appliance, and they're fine. So let's take a look at the data. We see that the highest-level tag is PurchaseOrder, which has several attributes: PoNum, OrderDate, and Status. Unlike relational data, where each element has its own column, or flat files where data is in specific locations, the data in an XML stream can come from anywhere within the document, subject to the syntactical rules of XML, which primarily revolve around surrounding data with tags. The attributes are a little different in that they are simply the keyword and the data joined by an equals sign (=), but the basic concept still applies: the name of the data is provided along with the data itself.

 

Then it can get very interesting. In this case, nested within that is an element named item, which we'll return to later. Just think about it for a moment, though; there could easily be zero, one, or a hundred item tags. That's where the straight one-to-one correspondence between an XML document and a single relational table beak down. I'll talk a little more about multiple instance tags before the article ends, but for now let's concentrate on the attributes and see just how we can express those attributes as a table.

 

Using the XMLTable Function

 

050615PlutaFigure1

Figure 1: The XMLTable function extracts attributes and elements and converts them to relational columns.

 

This one figure is jam-packed with information that may not be entirely intuitive at first glance. First, the select statement at the top tells you that we're going to be selecting some columns from the table purchaseorder, but that the columns will come from something we will define later and name xt (which stands for XML table). We're going to show all the columns from xt. The comma then segues into the actual XMLTable definition, which does quite a bit of work even in this simple example. The first parameter defines the path to the document, which starts first with a value preceded by a dollar sign. That value, $po, says that very soon you're going to define "po" as something that contains XML, and sure enough that happens in the next clause: passing porder as "po". That phrase says find the relational field porder; it will have XML in it and the top-level element will be named PurchaseOrder. Note that if the XML doesn't start that way, you won't get any rows.

 

The next clause starts with the keyword columns, which is appropriate, since it defines the columns being extracted from the XML. The first one is named OrderDate, and it comes from the attribute also named OrderDate. Similarly, the column Status comes from the tag Status. These column names do not have to match the tag names, but the tag name (the one following the path keyword) must match the tag in the XML. Also note that in this case, since OrderDate and Status are attributes and not elements, the attribute name is preceded by @. I still don't understand that, but it seems to be pretty standard through all the XML/SQL syntax: attribute names are preceded by @.

 

Done correctly, the XML will generate a nice table of data.

 

050615PlutaFigure2

Figure 2: This is the result of the XMLTable function in Figure 1.

 

This is nice, but it has one shortcoming; it shows only XML data. The result doesn't include any non-XML elements from the record. Our simple table contains, in addition to the XML field named PORDER, a number of traditional relational data fields. One of those is the POID field, which holds the PO number. This field is a duplicate of the PoNum attribute, but it will serve our purpose here of showing just how easy it is to combine relational data with XML elements.

 

050615PlutaFigure3

Figure 3: The XMLElement function embeds relational data within an XML element.

 

Here's a simple change that includes the POID field from the original record. You can see the statement is hardly changed, and it now includes a column from the relational table, as shown in the next figure.

 

050615PlutaFigure4

Figure 4: Adding the POID field in the statements yields the results you might expect.

 

Astute eyes might notice that I also changed the definition of the extracted OrderDate data. You can specify whatever type you like and, as long as the data in the element can be converted to the selected type, XML will do the conversion for you. You need to be careful with this as you would with any automatic conversion; if the data in the tag is bad, the selection will fail miserably.

 

That's it for this article. It really only scratches the surface of XMLTable. Subsequent articles will cover everything from handling multiple lines to using this syntax within a view: it can be very handy for selecting and sorting data from large XML documents. I hope this article convinces you to stay tuned for the upcoming ones!

 

BLOG COMMENTS POWERED BY DISQUS