Oracle中的LISTAGG给出了NULL

时间:2017-12-28 12:47:57

标签: sql database oracle12c listagg

如果列值太长,则listagg在Oracle 12c中给出NULL输出。造成这种情况的原因是什么?解决方案是什么?

SQL> select length(algo_desc) from r2_temp where DECL = '305';
     32759

ALGO_DESC非常长,如1045,2339,2389 ....... 37364,58922,2389392 现在如果我使用LISTAGG,那么它给出如下的NULL:

SQL> select dump(listagg(algo_desc, ',') within group (order by algo_desc)) as algo_desc from r2_temp where DECL = '305';
     NULL

列ALGO_DESC的最大大小为32767,它在12c中扩展了varchar2

1 个答案:

答案 0 :(得分:0)

作为一种解决方法,您可以使用此功能:

CREATE OR REPLACE TYPE VARCHAR_TABLE_TYPE AS TABLE OF VARCHAR2(32767);
-- or     CREATE OR REPLACE TYPE VARCHAR_TABLE_TYPE AS TABLE OF NUMBER;


CREATE OR REPLACE FUNCTION JoinTable(TAB IN VARCHAR_TABLE_TYPE, Joiner IN VARCHAR2) RETURN CLOB IS
    res CLOB;
BEGIN
    IF TAB IS NULL THEN 
        RETURN NULL; 
    END IF;
    IF TAB.COUNT = 0 THEN 
        RETURN NULL; 
    END IF;

    DBMS_LOB.CREATETEMPORARY(res, FALSE, DBMS_LOB.CALL);
    IF TAB(TAB.FIRST) IS NOT NULL THEN
        DBMS_LOB.APPEND(res, TAB(TAB.FIRST));
    END IF;
    IF TAB.COUNT > 1 THEN
        FOR i IN TAB.FIRST+1..TAB.LAST LOOP
            DBMS_LOB.APPEND(res, Joiner||TAB(i));
        END LOOP;
    END IF;
    RETURN res;

END JoinTable;



select JoinTable(CAST(COLLECT(algo_desc order by algo_desc) AS VARCHAR_TABLE_TYPE), ',') as algo_desc 
from r2_temp 
where DECL = '305';