获得第n个元素从去年在SQL Server中的XML
问题描述:
请考虑这个XML:获得第n个元素从去年在SQL Server中的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
,如果传递给我的函数,我将返回Jigha
。
答
这应该工作。将@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)