【问题标题】:Listagg function with PLSQL collectionListagg 函数与 PLSQL 集合
【发布时间】:2012-12-20 19:20:48
【问题描述】:

我有一个以下类型的 PL/SQL 集合

type p_typ_str_tab is table of varchar2(4000) index by pls_integer;

我想用一个简单的内联函数(如LISTAGG)将这些值聚合到一个字符串中,而无需编写任何自定义函数或 for 循环。 LISTAGG 的所有示例都没有显示如何使用 PL/SQL 集合。我正在使用 Oracle 11g R2。这可能吗?

【问题讨论】:

    标签: oracle collections plsql oracle11g aggregate-functions


    【解决方案1】:

    为了能够在集合中使用LISTAGG 函数,集合必须声明为嵌套表而不是关联数组,并且必须创建为 sql 类型(模式对象),因为无法使用 pl/sql 类型在选择语句中。为此,您可以执行以下操作:

    --- create a nested table type
    SQL> create or replace type t_tb_type is table of number;
      2  /
    
    Type created
    
    
    --- and use it as follows
    SQL> select listagg(column_value, ',') within group(order by column_value) res
      2    from table(t_tb_type(1,2,3)) -- or call the function that returns data of 
      3  /                              -- t_tb_type type
    
    RES
    -------
    1,2,3
    

    否则loop 是您唯一的选择。

    【讨论】:

      【解决方案2】:

      LISTAGG 是一个分析 SQL 函数,它们不针对 PL/SQL 集合操作,而是针对游标/行集。

      所以,简而言之,不,这是不可能的。

      也就是说,遍历 PL/SQL 表以构建串联字符串是微不足道的:

      l_new_string := null;
      for i in str_tab.first .. str_tab.last
      loop
        if str_tab(i) is not null then
          l_new_string := str_tab(i) || ', ';
        end if;
      end loop;
      -- trim off the trailing comma and space
      l_new_string := substr(l_new_string, 1, length(l_new_string) - 2);
      

      【讨论】:

      • 如此微不足道,您甚至犯了一个错误;)您的最终字符串仅包含最后一个条目-> l_new_string := l_new_string || str_tab(i) || ', '
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多