(一)语法:
Create Or Replace Function function_name (参数1,...)
Return collection Pipelined
Is
--声明部分
begin
--执行部分
pipe row(...); --填充元素
return;
exception
when others then
--异常处理部分
end;
(二)例子
例子1:
2 /
Type created
SQL> Create Or Replace Function Get_Nested_Table
2 Return nested_table Pipelined Is
3 i Number;
4 Begin
5 For i In 1..10 Loop
6 Pipe Row('第 '||i||' 个');
7 End Loop;
8
9 Return;
10 End;
11 /
Function created
SQL> Declare
2 nested_obj nested_table;
3 strCur Varchar2(3);
4 Begin
5 Select Get_Nested_Table Into nested_obj From dual;
6 If nested_obj.exists(1) Then
7 strCur:=nested_obj.first();
8 Loop
9 dbms_output.put_line(nested_obj(strcur));
10 Exit When strcur=nested_obj.last();
11 strcur:=nested_obj.next(strcur);
12 End Loop;
13 End If;
14 End;
15 /
第 1 个
第 2 个
第 3 个
第 4 个
第 5 个
第 6 个
第 7 个
第 8 个
第 9 个
第 10 个
PL/SQL procedure successfully completed
例子2:
SQL> Create Or Replace Type nested_table_base_type Is Object(Id Number,Name Varchar2(100))
2 /
Type created
SQL> Create Or Replace Type nested_table_type Is Table Of nested_table_base_type
2 /
Type created
SQL> Create Or Replace Function Get_Nested_Table
2 Return nested_table_type Pipelined Is
3 i Number;
4 Begin
5 For i In 1..10 Loop
6 Pipe Row(nested_table_base_type(i,'第 '||i||' 个'));
7 End Loop;
8 Return;
9 End;
10 /
Function created
SQL> Declare
2 nested_obj nested_table_type;
3 strCur Varchar2(3);
4 Begin
5 Select Get_Nested_Table Into nested_obj From dual;
6 If nested_obj.exists(1) Then
7 strCur:=nested_obj.first();
8 Loop
9 dbms_output.put_line(Rpad('id:'||nested_obj(strcur).id,6,' ')||' name:'||nested_obj(strcur).name);
10 Exit When strcur=nested_obj.last();
11 strcur:=nested_obj.next(strcur);
12 End Loop;
13 End If;
14 End;
15 /
id:1 name:第 1 个
id:2 name:第 2 个
id:3 name:第 3 个
id:4 name:第 4 个
id:5 name:第 5 个
id:6 name:第 6 个
id:7 name:第 7 个
id:8 name:第 8 个
id:9 name:第 9 个
id:10 name:第 10 个
PL/SQL procedure successfully completed
SQL>