Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate rows into CLOB

Tags:

sql

oracle

There are many similar questions on this subject, but I can't find any with solutions that keep into account anything with an end result too large for varchar2.

So what I'm trying to do is change this:

Column1 | Column2
-------- --------
1         Hello
1         world,
1         please help
2         Thanks
2         world,
2         you're the best.

Into this:

Column1 | Column2
-------- --------
1         Hello world, please help
2         Thanks world, you're the best.

My particular problem is that there are a few cases where the new concatenated value exceeds 4000 characters, so I can't use LISTAGG as I hoped to. I'm particularly interested in solutions without having to write a function, but either will do.

like image 832
JWiley Avatar asked Oct 22 '22 12:10

JWiley


2 Answers

As de.hh.holger already pointed out, the LISTAGG WITH CLOB? STRING AGGREGATION EXCEEDING 4000 CHARACTERS WITH XMLAGG does indeed solve this issue.

I have elaborated a little further on the subject and this should do the trick in case of a really long string message:

SELECT
   table_row_id,
   DBMS_XMLGEN.CONVERT (
     EXTRACT(
       xmltype('<?xml version="1.0"?><document>' ||
               XMLAGG(
                 XMLTYPE('<V>' || DBMS_XMLGEN.CONVERT(data_value)|| '</V>')
                 order by myOrder).getclobval() || '</document>'),
               '/document/V/text()').getclobval(),1) AS data_value
FROM (
   SELECT 1 myOrder, 1 table_row_id,'abcdefg>' data_value FROM dual
   UNION ALL
   SELECT 2, 1 table_row_id,'hijklmn' data_value FROM dual
   UNION ALL
   SELECT 3, 1 table_row_id,'opqrst' data_value FROM dual
   UNION ALL
   SELECT 4, 1 table_row_id,'uvwxyz' data_value FROM dual)
GROUP BY
   table_row_id
like image 173
Roeland Van Heddegem Avatar answered Oct 27 '22 09:10

Roeland Van Heddegem


SELECT Column1 , LISTAGG(Column2, ' ') 
WITHIN GROUP (ORDER BY Column2) AS employees
FROM   Table1
GROUP BY Column1 ;

Please have a look at this Article

like image 25
Prahalad Gaggar Avatar answered Oct 27 '22 08:10

Prahalad Gaggar