【问题标题】:Getting nth Element from last in a xml in Sql Server在Sql Server的xml中从最后一个获取第n个元素
【发布时间】:2013-06-13 18:27:18
【问题描述】:

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

【问题讨论】:

    标签: sql sql-server xml sql-server-2008


    【解决方案1】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-09
      • 1970-01-01
      • 2014-07-06
      • 2020-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多