2012-12-20 66 views
4

我有以下类型LISTAGG功能与PLSQL收集

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

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

回答

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 

否则loop是你唯一的选择。

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); 
+0

如此微不足道的是,Oracle没有内置函数...... –

+1

如此微不足道,甚至犯了一个错误;)您的最终字符串只包含最后一个条目 - > l_new_string:= l_new_string || str_tab(i)|| ',' – michalicekmilan