• Erland Sommarskog (7/26/2013)


    In XQuery (which is what you should use):

    DECLARE @x xml = '<bookstore>

    <book>

    <title lang="eng">Harry Potter</title>

    <price>29.99</price>

    </book>

    <book>

    <title lang="eng">Learning XML</title>

    <price>39.95</price>

    </book>

    </bookstore>'

    SELECT Title = T.c.value('(./text())[1]', 'varchar(29)'),

    Lang = T.c.value('@lang', 'varchar(23)'),

    Price = B.c.value('(price/text())[1]', 'decimal(10,2)')

    FROM @x.nodes('bookstore/book') AS B(c)

    CROSS APPLY B.c.nodes('title') AS T(c)

    To get an attribute, just use @attr. Element values are more clumsy, because you need this /text() because of performance, and [1] to avoid error messages. But this is the general pattern. Dig one level with APPLY nodes you want to use. (And never use parent-axis, .., because performance sucks in this case.)

    I was having trouble digging out the lang attribute and that's why I resorted to that silly subquery. Next time I'll have to remember to drop the [1].


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St