2010-07-08 75 views
2

如何将3或4个不同的值附加(插入)到oracle类型,然后再为游标打开它。如何将值附加到oracle类型

例如(伪):

insert into mytype select 1 from dual; 
insert into mytype select 3 from dual; 
insert into mytype select 5 from dual; 

open cursor_1 for select * from table(mytype); 

这是可能在PL/SQL办?

我知道这很简单,可以组合成一个查询,但我真正的需要是有不同的查询,并将结果附加到mytype。

回答

5

假设你的意思是你有一个自定义的SQL类型(可能是一个嵌套的表类型)和一个这种类型的PL/SQL变量:我不相信你可以INSERT进去,我认为你可以SELECT可以附加到集合中。

您可以选择一个标量变量,然后将其附加到程序集合中。

SQL> create type mytype as table of integer; 
    2/

Type created. 

SQL> set serveroutput on 
SQL> l 
    1 declare 
    2 mytable mytype := mytype(); 
    3 cursor_1 sys_refcursor; 
    4 x integer; 
    5 procedure append_to_table(t IN OUT mytype, y IN INTEGER) 
    6  is 
    7  begin 
    8  t.extend(); 
    9  t(t.COUNT) := y; 
10  end append_to_table; 
11 begin 
12 select 1 into x from dual; 
13 append_to_table(mytable, x); 
14 select 3 into x from dual; 
15 append_to_table(mytable, x); 
16 select 5 into x from dual; 
17 append_to_table(mytable, x); 
18 open cursor_1 for select * from table(cast(mytable as mytype)); 
19 fetch cursor_1 into x; 
20 dbms_output.put_line(x); 
21 fetch cursor_1 into x; 
22 dbms_output.put_line(x); 
23 fetch cursor_1 into x; 
24 dbms_output.put_line(x); 
25 close cursor_1; 
26* end; 
SQL>/
1 
3 
5 

PL/SQL procedure successfully completed. 
4

自10g以来,操作PL/SQL集合变得容易很多,它给了我们一些我们可以使用的SET操作符。

如你所知,聘请TABLE()函数意味着我们必须使用一个SQL类型...

SQL> create or replace type nums_nt as table of number 
    2/

Type created. 

SQL> 

以下块填充一些数字的集合,它使用一个FOR循环。然后它执行另一个查询来填充第二个集合。第二个集合使用MULTISET UNION语法添加到第一个集合中。与SQL UNION运算符不同,此实现不会重复出现(我们可以使用MULTISET UNION DISTINCT)。代码通过再次循环第一个集合完成,证明它包含两组数字。

SQL> set serveroutput on 
SQL> 
SQL> declare 
    2  master_nos nums_nt; 
    3  fresh_nos nums_nt; 
    4 begin 
    5 
    6  dbms_output.put_line ('get some numbers, print some names'); 
    7 
    8  select id 
    9  bulk collect into master_nos 
10  from t23 
11  where name not in (select upper(name) from t_doctors) 
12  and name not in (select upper(name) from t_kids); 
13 
14  for r in (select t23.name 
15     from t23 
16      join (select * from table(master_nos)) sq 
17        on t23.id = sq.column_value 
18    ) 
19  loop 
20   dbms_output.put_line (r.name); 
21  end loop; 
22 
23  dbms_output.put_line ('get more numbers, print all names'); 
24 
25  select id 
26  bulk collect into fresh_nos 
27  from t23 
28  where name in (select upper(name) from t_doctors); 
29 
30  master_nos := master_nos 
31      MULTISET UNION 
32     fresh_nos; 
33 
34  for r in (select t23.name 
35     from t23 
36      join (select * from table(master_nos)) sq 
37        on t23.id = sq.column_value 
38    ) 
39  loop 
40   dbms_output.put_line (r.name); 
41  end loop; 
42 
43 end; 
44/
get some numbers, print some names 
CAT 
PINNER BLINN 
LORAX 
MR KNOX 
FOX IN SOCKS 
get more numbers, print all names 
CAT 
PINNER BLINN 
LORAX 
MR KNOX 
FOX IN SOCKS 
DR SINATRA 
DR FONZ 

PL/SQL procedure successfully completed. 

SQL>