带有PLSQL集合的Listagg函数

Ale*_*lex 4 oracle collections plsql aggregate-functions oracle11g

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

type p_typ_str_tab is table of varchar2(4000) index by pls_integer;
Run Code Online (Sandbox Code Playgroud)

我想用一个简单的内联函数将值聚合成一个字符串,就像LISTAGG不编写任何自定义函数或for循环一样.所有示例LISTAGG都没有显示如何使用PL/SQL集合.我正在使用Oracle 11g R2.这可能吗?

Nic*_*nov 9

为了能够对LISTAGG集合使用函数,必须将集合声明为嵌套表而不是关联数组,并且必须将其创建为sql类型(模式对象),因为无法在select语句中使用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
Run Code Online (Sandbox Code Playgroud)

否则,这loop是你唯一的选择.


Ada*_*sch 5

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);
Run Code Online (Sandbox Code Playgroud)