2015-12-02 34 views
0

我有如下一個XML結構:如何編寫選擇查詢以選擇多次出現的DB2中特定的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將返回其具有a1作爲someText1和a2爲someNumber1所有的應用程序ID。

欲瞭解更多信息,我有一個表說應用程序具有application_xml列。該列具有上面所示的所有xml文檔,並針對每個應用程序標識進行存儲。

有人可以請建議。

我試過下面的查詢,但沒有成功。

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 

回答

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」的條件都必須爲真。如果你想要更廣泛的條件,也會有方法來表達這一點。

+0

我明白你的答案。但是,您能否指點我一個DB2 XML查詢的好資源,以便我不用擔心語法問題。 – Sam

+0

您可以從DB2知識中心開始:http://www-01.ibm.com/support/knowledgecenter/SSEPGG_10.5.0/com.ibm.db2.luw.xml.doc/doc/c0023895.html?lang = EN –