I have a query such as this-
WITH xtbl AS (SELECT xmltype ('<root>
<parent>
<item>
<item_detail>AAA</item_detail>
<item_amount>1000</item_amount>
</item>
<item>
<item_detail>BBB</item_detail>
<item_amount>2000</item_amount>
</item>
</parent>
</root>') AS xcol FROM dual)
SELECT xmlcast (
xmlquery ('root/parent/string-join[item/item_detail/text()]' PASSING xcol RETURNING CONTENT) AS VARCHAR2 (2000))
AS item_details
FROM xtbl;
Although the example specified above contains an node, in my real problem not every <parent> node will contain an <item> node. Thus I cannot use the XMLTable solution as described in this answer.
The SELECT xmlcast(... query is what I have tried so far above and it isn't working. My expected output is this-
ITEM_DETAILS
------------------
AAA 1000, BBB 2000
Please suggest how I can modify my XMLQuery.
You can use an XMLTable call still:
and then concatenate and aggregate:
For a parent with no items that will just return null.
However, you can also do it with an XMLQuery call:
and again with a parent with no items that just returns null.
The
let $d :=part concatenates the detail and amount for each item, with a space between them, usingconcat(). Then all the$dvalues that generates are aggregated usingstring-join().That returns an XMLType, so to get the result as a plain string you can use XMLCast as in your question, or more simply use
.getStringVal():