DooDoo
DooDoo

Reputation: 13447

Getting nth Element from last in a xml in Sql Server

Please consider this XML:

<Employees>
    <Person>
        <ID>1000</ID>
        <Name>Nima</Name>
        <LName>Agha</LName>
    </Person>
    <Person>
        <ID>1001</ID>
        <Name>Ligha</Name>
        <LName>Ligha</LName>
    </Person>
    <Person>
        <ID>1002</ID>
        <Name>Jigha</Name>
        <LName>Jigha</LName>
    </Person>
    <Person>
        <ID>1003</ID>
        <Name>Aba</Name>
        <LName>Aba</LName>
    </Person>
</Employees>

I want to write a function that gets a number, and then I get nth Person element, and Name. For example if 0 pass to my function I return Aba, if 1 pass to my function I return Jigha.

Upvotes: 2

Views: 5654

Answers (1)

Ed Harper
Ed Harper

Reputation: 21505

This should work. Set the value of the @index variable as the number of the record to find, relative to the end of the list:

declare @index int = 1
declare @xml xml = '<Employees>
    <Person>
        <ID>1000</ID>
        <Name>Nima</Name>
        <LName>Agha</LName>
    </Person>
    <Person>
        <ID>1001</ID>
        <Name>Ligha</Name>
        <LName>Ligha</LName>
    </Person>
    <Person>
        <ID>1002</ID>
        <Name>Jigha</Name>
        <LName>Jigha</LName>
    </Person>
    <Person>
        <ID>1003</ID>
        <Name>Aba</Name>
        <LName>Aba</LName>
    </Person>
</Employees>'

select t2.person.value('(Name/text())[1]','varchar(50)')
from @xml.nodes('Employees/Person[position()=(last()-sql:variable("@index"))]') as t2(person)

Upvotes: 9

Related Questions