Oracle SQL: Handling Excessively Long String Concatenation with XMLAGG
Oracle's LISTAGG function is a useful tool for combining string values into a single, comma-separated list. However, it's limited by a maximum string length. When the concatenated result exceeds this limit, an "ORA-01489: result of string concatenation is too long" error occurs.
This problem surfaced when attempting to concatenate WEB_LINK data using LISTAGG in Oracle SQL Developer. The WEB_LINK field, containing combined URL stems and queries, often resulted in strings exceeding the allowed length.
The solution? The XMLAGG function. Unlike LISTAGG, XMLAGG returns a CLOB (character large object), capable of handling significantly longer strings, effectively removing row count limitations.
Here's the revised query using XMLAGG:
<code class="language-sql">SELECT RTRIM(XMLAGG(XMLELEMENT(E, colname, ',').EXTRACT('//text()') ORDER BY colname).GetClobVal(), ',') AS LIST FROM tablename;</code>
This approach successfully aggregates and concatenates the data, even with very long strings, returning the result as a CLOB. This provides a robust alternative to LISTAGG when dealing with potentially oversized string concatenation in data aggregation tasks.
The above is the detailed content of How Can XMLAGG Overcome the 'ORA-01489: result of string concatenation is too long' Error When Using LISTAGG in Oracle SQL?. For more information, please follow other related articles on the PHP Chinese website!