Getting nth Element from last in a xml in Sql Server(从 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 个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 Sql Server 中的 xml 中的最后一个获取第 n 个元素


基础教程推荐
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 在多列上分布任意行 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01