How do you get a node that contains a child node with a given attribute value in an XML document using sql server?(如何使用 sql server 在 XML 文档中获取包含具有给定属性值的子节点的节点?)
问题描述
我正在使用 SQL Server 2008 解析 XML 文档.我是一个完整的菜鸟,我想知道我是否可以从你们那里得到帮助.
I'm working on parsing XML documents using SQL Server 2008. I'm a complete noob and I was wondering if I can get help from you guys.
我有一个像下面这样的 XML 文档,我想获取代码"节点具有 val=5 的部分"节点.
I have an XML document like the one below and I want to get the "section" node where the "code" node has val=5.
<root>
<section>
<code val=6 />
...
</section>
<section>
<code val=5 />
...
</section>
<section>
<code val=4 />
...
</section>
</root>
所以结果应该是:<代码><节><代码val=5/>...</section>
我试过这样做,但没有用:
I tried doing this, but it didn't work:
select @xml.query('/root/section')其中@xml.value('/root/section/code/@val,'int')='5'
我也试过这个:select @xml.query('/root/section')其中@xml.exist('/root[1]/section[1]/code[@val="1"])='1'
有什么想法吗?提前致谢.
Any ideas? Thanks in advance.
推荐答案
你可以使用这个查询:
DECLARE @x XML=N'
<root>
<section atr="A">
<code val="5" />
</section>
<section atr="B">
<code val="6" />
</section>
<section atr="C">
<code val="5" />
</section>
</root>';
SELECT a.b.query('.') AS SectionAsXmlElement,
a.b.value('@atr','NVARCHAR(50)') AS SectionAtr
FROM @x.nodes('/root/section[code/@val="5"]') a(b);
结果:
SectionAsXmlElement SectionAtr
------------------------------------------- ----------
<section atr="A"><code val="5" /></section> A
<section atr="C"><code val="5" /></section> C
这篇关于如何使用 sql server 在 XML 文档中获取包含具有给定属性值的子节点的节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 sql server 在 XML 文档中获取包含具有给定
基础教程推荐
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- oracle区分大小写的原因? 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 在多列上分布任意行 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
