使用记录类型变量只能保存一行数据,这限制了SELECT语句的返回行数,如果SELECT语句返回多行就会错。Oracle提供了另外一种自定义类型,也就是表类型,它是对记录类型的扩展,允许处理多行数据,类似于表。
创建表类型的语法如下:
TYPE table_name IS TABLE OF data_type [ NOT NULL ]
INDEX BY BINARY_INTEGER ;
语法说明如下:
--table_name 创建的表类型名称。
--IS TABLE 表示创建的是表类型。
创建表类型的语法如下:
TYPE table_name IS TABLE OF data_type [ NOT NULL ]
INDEX BY BINARY_INTEGER ;
语法说明如下:
--table_name 创建的表类型名称。
--IS TABLE 表示创建的是表类型。
--data_type 可以是任何合法的PL/SQL数据类型,例如varchar2。
--INDEX BY BINARY_INTEGER 指定系统创建一个主键索引,用于引用表类型变量中的特定行。
例子1:
通过变量循环赋值表类型,再循环输出
declare
type my_table is table of testtable%rowtype
index by binary_integer;
new_table my_table;
i int;
j int;
begin
i := 1;
j := 5;
for t in i..j loop
new_table(t).id := t;
new_table(t).name := t;
end loop;
for t in i..j loop
Dbms_Output.put_line(new_table(t).id||new_table(t).name);
end loop;
end;
示例2:
结合表,实现循环表记录
declare
type my_table is table of testtable%rowtype
index by binary_integer;
new_table my_table;
i int;
j int;
rn int;
begin
i := 1;
select count(*) into j from testtable;
for t in i..j loop
select id,name into new_table(t).id,new_table(t).name from(select t.*,rownum rn from(select * from testtable) t
where rownum <t+1) where rn >= t;
end loop;
for t in i..j loop
Dbms_Output.put_line(new_table(t).id||new_table(t).name);
end loop;
end;