• Here's one way. Not sure it's the best way and it doesn't use OPENXML though:

    DECLARE @Books XML = '

    <bookstore>

    <book>

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

    <price>29.99</price>

    </book>

    <book>

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

    <price>39.95</price>

    </book>

    </bookstore>'

    SELECT title

    ,[language]=(

    SELECT TOP 1 z.value('@lang[1]', 'VARCHAR(1000)')

    FROM x.nodes('bookstore/book/title') c(z)

    WHERE title = z.value('(.)[1]', 'VARCHAR(1000)')

    )

    ,price=y.value('(price)[1]', 'MONEY')

    FROM (SELECT @Books) a(x)

    CROSS APPLY x.nodes('bookstore/book') b(y)

    CROSS APPLY (SELECT title=y.value('(title)[1]', 'VARCHAR(1000)')) c

    Note the TOP 1 on the correlated sub-query is there in case the same book title appears with multiple languages. In that case, the sub-query won't return the correct result but at least won't fail. To correct a case like that, you'd need to have something unique in the correlation like ISBN.

    Edit: Added the second CROSS APPLY to clean it up a little.


    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