sql >> Base de Datos >  >> RDS >> Oracle

¿Por qué aparece el siguiente error en la función LISTAGG:“el resultado de la concatenación de cadenas es demasiado largo?*

Como ya dijeron otros comentaristas, no hay forma de evitar dicho error hasta Oracle 12.2 (donde List_agg tiene la nueva opción "ON OVERFLOW TRUNCATE").

En versiones anteriores de Oracle, si concatena cadenas de más de 4000 bytes, obtiene ese error. NO tienes forma de prevenirlo.

Si aún necesita hacer eso en versiones anteriores, debe escribir su propia función para hacerlo y debe modificar su consulta en consecuencia:

Esta función personalizada podría resolver su problema

 create or replace type TAB_STRINGS is table of varchar2(4000) 
 /
 create or replace function My_list_agg(strings in TAB_STRINGS,
                      separator  in varchar2,
                      max_len    integer) return varchar2 deterministic is
   result varchar2(32000);
   tmp    varchar2(32000);
 begin
   result := null;
   if strings is not null then
       for idx in strings.first .. strings. last loop
         tmp := strings(idx);
         if tmp is not null then
           if result is null then
             exit when length(tmp) > max_len;
             result := tmp;
           else
             exit when(length(result) + length(separator) + length(tmp)) > max_len;
             result := result || separator || tmp;
           end if;
         end if;
       end loop;
   end if;
   return result;
 end;
 /

necesita usar el operador CAST/COLLECT para usarlo.
este es un ejemplo de uso:

   select table_name,
          My_list_agg(  
                 -- first argument: array of strings to be concatenated
                 cast ( collect (column_name order by column_name) as TAB_STRINGS),
                 -- second (optional) argument: the separator
                 ',',
                 -- third argument (optional): the maximum length of the string to be returned
                 1000   
          ) as column_list
   from user_tab_columns t
   group by table_name
   order by table_name