从 Sql Server 中的 xml 中的最后一个获取第 n 个元素 [英] Getting nth Element from last in a xml in Sql Server

查看:37
本文介绍了从 Sql Server 中的 xml 中的最后一个获取第 n 个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑这个 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>

我想写一个函数来获取一个数字,然后我得到第n个Person元素和Name.例如,如果 0 传递给我的函数,我返回 Aba,如果 1 传递给我的函数,我返回 Jigha.

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.

推荐答案

这应该有效.将 @index 变量的值设置为要查找的记录的编号,相对于列表的末尾:

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)

这篇关于从 Sql Server 中的 xml 中的最后一个获取第 n 个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆