简体   繁体   English

在 Oracle 查询中连接 XMLType 节点

[英]Concatenate XMLType nodes in Oracle query

I have a CLOB column that contains XML type data.我有一个包含 XML 类型数据的 CLOB 列。 For example XML data is:例如 XML 数据是:

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

I have tried the concat function:我试过concat函数:

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.最后,不是在每个<B>标签之后。

I am currently using我目前正在使用

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

I want to concatenate all <B> with ;我想连接所有<B>; and expected result should be 123;789预期结果应为123;789

Please suggest me how can I concatenate my data.请建议我如何连接我的数据。

The concat() SQL function concatenates two values, so it's just appending the semicolon to each extracted value independently. concat() SQL 函数连接两个值,因此它只是将分号独立地附加到每个提取的值。 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 而不是提取,并使用 XPath string-join()函数进行连接:

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

Demo with fixed XMl end-node tags:带有固定 XMl 端节点标签的演示:

-- 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:您还可以使用 XMLTable 提取所有单独的<B>值,然后使用 SQL 级聚合:

-- 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.这为您提供了更大的灵活性,并允许更轻松地按其他节点值进行分组,但根据您的示例值,这里似乎不需要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM