Friday, February 28, 2014

Xquery

Alright, so I'm ready to dive into some Xquery discussions…

Xquery, is just as it sounds that you can query information from and XML document.  The thing that I had a hard time understanding about Xquery was due to the fact that I had been studying so much TSQL, and was comfortable with SELECT, FROM WHERE, ORDER BY, etc… and I assumed that the result that I would get from Xquery would be represented as a normal value that you could then use somewhere else (a CTE, apply, SELECT INTO).  It's  little different than that… while you can shread XML data into "normal" looking columns, most of the time the results that your query returns is in and XML format (a format that you can specify) which is one of the GOOD things about XML.

So to start with, going back to my example yesterday of the Bagdad Theater in Portland, OR… the XML looked like this:

<usa>
  <or>
    <portland>
      <southeast>
        <hawthorn>
          <thirtyseventh>
            <BagdadTheater>SeatThree</BagdadTheater>
          </thirtyseventh>
        </hawthorn>
      </southeast>
    </portland>
  </or>
</usa>


Well you have to turn this into an XML document, which would be a declaration like this (modified it and added data as you'll notice):

DECLARE @abc AS XML;
SET @abc = N '
<usa>
  <or>
    <portland>
      <southeast>
        <hawthorn>
          <thirtyseventh>
            <BagdadTheater>SeatThree</BagdadTheater>
          </thirtyseventh>
        </hawthorn>
      </southeast>
    </portland>
  </or>
</usa>'


Now we can query @abc

SELECT @abc.query('*') AS Complete_Sequence, 

That query is going to give us back the complete XML document (@abc).  

You can also query specific areas of the document:

SELECT @abc.query('data(usa/or/portland/southeast/hawthorn/37ave/BagdadTheater)') AS Element_theaterseat_data

Can you guess what would be returned?

A big piece of Xquery is the use of FLWOR (I call it flower) which stands for FOR, LET, WHERE, ORDER, RETURN.  FLWOR is similar to SELECT, FROM, WHERE in SQL when querying tables.  

In the example above we could use the FLWOR to get the same result, it would look like this:

FOR  $x in doc("Theater.XML")/usa/or/portland/southeast/hawthorn/37ave
LET $x /BagdadTheater
RETURN $x (I'm not sure about this part, so don't quote me on it)

This gives you an idea of how Xquery works… I've began to think about XML really as a big array that we've developed paths for and modes of navigation to move around.  I still think the best way to get comfortable with some XML is to work out some problems with it.  The book gives some very simple practice lessons that I am going to try, anyone else who is reading this and is at the same level as me I encourage to do the same thing!…. I hope this helps!

No comments:

Post a Comment