Ben Thul
Ben Thul

Reputation: 32707

First child in xml document using SQLXML

I have an bit of XML that I want to get the first child from. So far, I've been able to do it thusly:

DECLARE @x XML = '<a><b foo="bar">some data</b><b foo="baz"/></a>'
SELECT @x.query('(/a/child::*)[1]')

I'm just wondering if there's a more efficient way. My problem is that the element following the "a" tag is unknown to me until run-time, so just saying

@x.query('(/a/b)[1]')

isn't going to work for me. The tag after "a" could just as well be "c" and I'd like for one query to account for that.

Upvotes: 0

Views: 2525

Answers (2)

Mark Costello
Mark Costello

Reputation: 4394

This should work for you:

SELECT @x.query('(/a/*[1])')

Upvotes: 0

Sean Reilly
Sean Reilly

Reputation: 21836

Try this:

DECLARE @x XML = '<a><b foo="bar">some data</b><b foo="baz"/></a>'
SELECT @x.query('(/a/*)[1]')

It's actually the exact same query under the hood, as the child axis is the default one in xpath. Also, this should be efficient.

Upvotes: 1

Related Questions