mark
mark

Reputation: 11

SQL Server XML node value

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

Upvotes: 1

Views: 76

Answers (1)

Leandro Angelo
Leandro Angelo

Reputation: 111

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)

Upvotes: 1

Related Questions