1

From within SQL Server, I want to get the nth (2nd) tag value within a XML object record

declare @xml xml = 
'<animals>
    <dog>
        <petname>fred</petname>
    </dog>
    <cat>
        <petname>bill</petname>
    </cat>
</animals>'

select 
    n.value('petname[1]','varchar(10)') as name,
    n.value('../(*).name()[1]','varchar(10)') as animalType  -- don't know how to get this???
from 
    @xml.nodes('animals/*') as a(n)

The results I want:

name   animalType
-----------------
fred   dog
bill   cat

Thanks

1 Answer 1

1

Did you try the local-name?

declare @xml xml = 
'<animals>
    <dog>
        <petname>fred</petname>
    </dog>
    <cat>
        <petname>bill</petname>
    </cat>
</animals>'

select 
n.value('petname[1]','varchar(10)') as name,
n.value('local-name(.)','varchar(10)') as animalType
from @xml.nodes('animals/*') as a(n)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.