我有一个XML结构如下:
<root>
<firstChild>
<a>
<a1>someText</a1>
<a2>someNumber</a2>
<a>
<a>
<a1>someText1</a1>
<a2>someNumber1</a2>
<a>
<a>
<a1>someText2</a1>
<a2>someNumber2</a2>
<a>
<a>
<a1>someText3</a1>
<a2>someNumber3</a2>
<a>
</firstChild>
</root>
我想编写一个DB2 SQL,它将返回所有应用程序ID,其中a1为someText1,a2为someNumber1。
有关更多信息,我有一个表说APPLICATION,其中application_xml为列。此列包含如上所示的所有xml文档,并针对每个应用程序ID进行存储。
有人可以建议。
我试过下面的查询,但没有成功。
select XMLQUERY('copy $new := $application_xml
for $i in $new/root/firstChild/a[a1 = "someText1"], $new/root/firstChild/a[a2 = "someNumber1"]
return $new') from application
答案 0 :(得分:1)
根据您的描述,我假设该表有两列application id(aid)和application_xml。如果要返回应用程序ID,则查询的基本结构为
select aid from application
现在我们需要符合哪些行的条件。您声明在相关的XML文档中,元素a1和a2需要具有特定值。函数xmlexists
是在SQL的WHERE
子句中使用的函数:
select aid from application
where xmlexists('$d/root/firstChild/a[a1 = "someText1" and a2 = "someNumber1"]' passing application_xml as "d")
XMLEXISTS用作过滤谓词。 “传递”子句告诉DB2在XPath / XQuery表达式中的名称“d”下需要“application_xml”。 XPath表达式本身正在寻找路径/root/firstChild/a
,在特定的“a”下,“a1”和“a2”的条件都需要为真。如果你想要一个更广泛的条件,那么也有办法表达这一点。