Concatenate XMLType nodes in Oracle query

放肆的年华 提交于 2021-02-05 09:13:01

问题


I have a CLOB column that contains XML type data. For example XML data is:

<A><B>123</b><C>456</C><B>789</b></A>

I have tried the concat function:

concat(xmltype (a.xml).EXTRACT ('//B/text()').getStringVal (),';'))

or

xmltype (a.xml).EXTRACT (concat('//B/text()',';').getStringVal ()))

But they are giving ";" at end only not after each <B> tag.

I am currently using

xmltype (a.xml).EXTRACT ('//B/text()').getStringVal () 

I want to concatenate all <B> with ; and expected result should be 123;789

Please suggest me how can I concatenate my data.


回答1:


The concat() SQL function concatenates two values, so it's just appending the semicolon to each extracted value independently. But you're really trying to do string aggregation of the results (which could, presumably, really be more than two extracted values).

You can use XMLQuery instead of extract, and use an XPath string-join() function to do the concatentation:

XMLQuery('string-join(/A/B, ";")' passing xmltype(a.xml) returning content)

Demo with fixed XMl end-node tags:

-- CTE for sample data
with a (xml) as (
  select '<A><B>123</B><C>456</C><B>789</B></A>' from dual
)
-- actual query
select XMLQuery('string-join(/A/B, ";")' passing xmltype(a.xml) returning content) as result
from a;

RESULT
------------------------------
123;789

You could also extract all of the individual <B> values using XMLTable, and then use SQL-level aggregation:

-- CTE for sample data
with a (xml) as (
  select '<A><B>123</B><C>456</C><B>789</B></A>' from dual
)
-- actual query
select listagg(x.b, ';') within group (order by null) as result
from a
cross join XMLTable('/A/B' passing xmltype(a.xml) columns b number path '.') x;

RESULT
------------------------------
123;789

which gives you more flexibility and would allow grouping by other node values more easily, but that doesn't seem to be needed here based on your example value.



来源:https://stackoverflow.com/questions/55472173/concatenate-xmltype-nodes-in-oracle-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!