17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Notice that our order count remained a text element of the row — only the column that we identified as<br />

an attribute moved in. We could take this to the next step by naming our count and prefixing it to make<br />

it an attribute also:<br />

SELECT CustomerID AS '@CustomerID',<br />

COUNT(*) AS '@OrderCount'<br />

FROM Sales.SalesOrderHeader Orders<br />

WHERE CustomerID = 29890 OR CustomerID = 30067<br />

GROUP BY CustomerID<br />

FOR XML PATH;<br />

With this, we no longer have our loose text for the element:<br />

<br />

<br />

Also notice that <strong>SQL</strong> <strong>Server</strong> was smart enough to realize that everything was contained in attributes —<br />

with no lower level elements or simple text, it chose to make it a self-closing tag (see the “/” at the end<br />

of the element).<br />

So, why did I indicate that this stuff was tricky? Well, there are a lot of different “it only works if . . .”<br />

kind of rules here. To demonstrate this, let’s make a simple modification to our original query. This one<br />

seems like it should work, but <strong>SQL</strong> <strong>Server</strong> will throw a hissy fit if you try to run it:<br />

SELECT CustomerID,<br />

COUNT(*) AS ‘@OrderCount’<br />

FROM Sales.SalesOrderHeader Orders<br />

WHERE CustomerID = 29890 OR CustomerID = 30067<br />

GROUP BY CustomerID<br />

FOR XML PATH;<br />

What I’ve done here is to go back to CustomerID as its own element. What, at first glance, you would<br />

expect to happen is to get a CustomerID element with OrderCount as an attribute, but it doesn’t quite<br />

work that way:<br />

Msg 6852, Level 16, State 1, Line 1<br />

Attribute-centric column '@OrderCount' must not come after a non-attribute-centric<br />

sibling in XML hierarchy in FOR XML PATH.<br />

The short rendition of the “What’s wrong?” answer is that it doesn’t really know what it’s supposed to<br />

be an attribute of. Is it an attribute of the row, or an attribute of the CustomerID?<br />

Yes, a forward slash.<br />

Chapter 16: A Brief XML Primer<br />

Much like @, this special character indicates special things you want done. Essentially, you use it to<br />

define something of a path — a hierarchy that relates an element to those things that belong to it. It can<br />

exist anywhere in the column name except as the first character. To demonstrate this, we’re going to utilize<br />

our last (failed) example, and build into it what we were looking for when we got the error.<br />

507

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!