db2 SQL XMLQUERY LOOP

时间:2016-10-31 11:44:49

标签: sql xml select db2

<phone type="work">905-555-7258</phone>
<phone type="home">416-555-2937</phone>
<phone type="cell">905-555-8743</phone>
<phone type="cottage">613-555-3278</phone>
...

SELECT
        XMLCAST(XMLQUERY    ('$d/customerinfo/phone[n]/@type'
                        PASSING INFO AS "d") as VARCHAR(128)) type,
        XMLCAST(XMLQUERY    ('$d/customerinfo/phone[n]'
                        PASSING INFO AS "d") as VARCHAR(128)) number
FROM CUSTOMER;

如何选择n个电话号码?我正在考虑像for循环(java)这样的东西,但我无法在SQL for DB2中找到一种方法。 有什么想法吗?

1 个答案:

答案 0 :(得分:1)

将CTE与ROW_NUMBER结合使用:

SELECT * FROM
(
SELECT ROW_NUMBER() OVER() N,X.*
FROM XMLTABLE ('$cust/customerinfo/phone' PASSING 
XMLPARSE(CLOB('<customerinfo Cid="1003">
  <name>Robert Shoemaker</name>
    <addr country="Canada">
    <street>1596 Baseline</street>
    <city>Aurora</city>
    <prov-state>Ontario</prov-state>
    <pcode-zip>N8X 7F8</pcode-zip>
  </addr>
  <phone type="work">905-555-7258</phone>
  <phone type="home">416-555-2937</phone>
  <phone type="cell">905-555-8743</phone>
  <phone type="cottage">613-555-3278</phone>
</customerinfo>')) as "cust"
   COLUMNS 
   "PHONETYPE" CHAR(30) PATH '@type',
   "PHONENUM" CHAR(15) PATH '.'
  ) as X
) AS phones
WHERE 
N=4