1. 程式人生 > >Oracle 實現多行轉換成一行 使用oracle 10g collect函式

Oracle 實現多行轉換成一行 使用oracle 10g collect函式

在Oracle 10g中,新增加了一個聚合函式

collect:Takes a column of any type and creates a nested table of the input type out of the rows selected

1、建立陣列型別

create or replace type varchar2_app as table of varchar2(2000);

2、建立format_string格式化輸出函式

create or replace function format_string(v_table in varchar2_app) return varchar2 is
  Results varchar2(30000);
begin
  for i in 1 .. v_table.count loop
    Results :=Results||','||v_table(i);
  end loop;
 --去掉第一個逗號--
 return(substr(Results,2));
end format_string;
3、開始使用
select object_type, 
       format_string(CAST(COLLECT(object_name) AS varchar2_app)) AS object_name 
from user_objects 
group by object_type;

注意:

COLLECT函式後要用型別varchar2_app陣列型別