从 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)
相关文章