I have an Oracle DB CLOB field which stores xml in it. I need to retrieve all values in all the xml with DistributionNbr tag I have used the below query for the same and providing a sample xml for ref.
select extract(xmltype(column_name),'//*/xmlpath/text()').getStringval() as g
from table;
<xml>
<ShipConfirm>
<ShipmentID>000000196</ShipmentID>
</ShipConfirm>
<ShipConfirm>
<ShipmentID>000000197</ShipmentID>
</ShipConfirm>
<ShipConfirm>
<ShipmentID>000000198</ShipmentID>
</ShipConfirm>
</xml>
Now I am getting values as a single string: 000000196000000197000000198
I need to get a comma separated value or value in next line. 000000196,000000197,000000198
OR
000000196
000000197
000000198
Use XMLTABLE
:
SELECT x.ShipmentID
FROM your_table t
CROSS JOIN
XMLTABLE(
'//xml/ShipConfirm'
PASSING XMLTYPE( t.column_name )
COLUMNS ShipmentID CHAR(9) PATH './ShipmentID'
) x;
That will return it in rows.
If you want it as comma-delimited values then you can use:
SELECT LISTAGG( x.ShipmentID, ',' ) WITHIN GROUP ( ORDER BY idx )
AS ShipmentIDs
FROM your_table t
CROSS JOIN
XMLTABLE(
'//xml/ShipConfirm'
PASSING XMLTYPE( t.column_name )
COLUMNS ShipmentID CHAR(9) PATH './ShipmentID',
idx FOR ORDINALITY
) x
GROUP BY t.primary_key;
Please avoid unnecessary '//' operators... and the column patterns are implicitly relative to the row pattern
SQL> with MY_TABLE as
2 (
3 select 1 as PRIMARY_KEY,
4 XMLTYPE(
5 '<xml>
6 <ShipConfirm>
7 <ShipmentID>000000196</ShipmentID>
8 </ShipConfirm>
9 <ShipConfirm>
10 <ShipmentID>000000197</ShipmentID>
11 </ShipConfirm>
12 <ShipConfirm>
13 <ShipmentID>000000198</ShipmentID>
14 </ShipConfirm>
15 </xml>') as XML_DOC
16 from DUAL
17 )
18 SELECT LISTAGG( x.ShipmentID, ',' ) WITHIN GROUP ( ORDER BY idx ) AS ShipmentIDs
19 FROM MY_TABLE t,
20 XMLTABLE(
21 '/xml/ShipConfirm'
22 PASSING XML_DOC
23 COLUMNS
24 idx FOR ORDINALITY,
25 ShipmentID CHAR(9) PATH 'ShipmentID'
26 ) x
27 GROUP BY t.primary_key
28 /
SHIPMENTIDS
--------------------------------------------------------------------------------
000000196,000000197,000000198
SQL>
SQL>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.