Oracle集合

oracle的集合一共有三种:1.关联数组;2.嵌套数组;3.VARRAY(可变长度数组)
1.关联数组
其定义语法是:type 数组名称 is table of 元素类型 index by 索引类型.
索引类型可以是varchar2类型和pls_integer类型.例如:
declare
   --定义一个关联数组类型
   type student_list is table of student%rowtype index by pls_integer;
   --声明关联数组变量
   student_list_var student_list;
   --定义一个游标
   cursor student_cursor is 
     select * from student;
begin
   --循环游标,其中student_index相关于基于游标的记录
   for student_index in student_cursor
   loop
     --其中id是表student的列number类型,以下是记录之间的赋值.个人认为关联数组和java中的功能map很像
     student_list_var(student_index.id) := student_index;
   end loop;

2.嵌套数组
语法:type 数组名称 is table of 元素类型
例如:
--定义一个名字数组
type list_of_name is table of varchar2(100);
--定义一个学生数组,其中student为表
type list_of_student is table of student%rowtype;

使用示例:
--创建一个嵌套数组
create type student_table is table of student%rowtype;
--定义一个根据学生姓名查询学生列表的函数
create or replace of function list_studect(student_name in student.name%type) return student_table is
  --根据学生姓名查询学生列表游标
  cursor student_cursor(student_name in student.name%type) is
    select * from student where name like student_name||'%';
  --声明基于表的学生记录
  student_var student%rowtype;
  --声明一个嵌套数组变量
  student_table_var student_table;
  --声明拓展嵌套数组的下标
  index_var pls_integer := 0;
begin
  --初始化嵌套数组
  student_table_var =: student_table();
  --循环游标
  for cur_index in student_cursor(student_name)
  loop
    --拓展嵌套数组
    student_table_var.extend;
    --下标以1开始,时,嵌套数组是非稀疏的
    index_var := index_var + 1;
    --赋值
    student_table_var(index_var) := cur_index;
  end loop;
  return student_table_var;
end;

3.VARRAY(可变长度数组)
语法:type 数组名称 is varray(数组长度) of 元素类型
例如:
--定义一个名字可变长度数组
type list_of_name is varray(100) of varchar2(100);
--定义一个学生可变长度数组,其中student为表
type list_of_student is varray(500) of student%rowtype;

VARRAY的使用和嵌套表差不多,唯一的区别是VARRAY是有长度限制的.
他们的区别如下图所示:
属性 关联数组 嵌套表 varray
纬度 一维 一维 一维
是否可用于SQL 不可用 可用 可用
是否可作为表中列的数据类型 不可用 可用 可用
为初始化的状态 空(不能是NULL)元素是未定义 自动是NULL,对元素的引用是非法的 自动是NULL,对元素的引用是非法的
初始化 在声明时自动完成 通过构造函数,或者赋值,或者fetch操作完成 通过构造函数,或者赋值,或者fetch操作完成
是否稀疏 开始不是;经过删除后就是了 不是
是否有界 无界 可以扩展 不是
可以随时对任意一个元素赋值 可以 不可以,可以需要先用extend进行扩展 不可以;可以需要先用extend进行扩展,而且extend扩展时不能超过上边界
扩展方法 给一个新下标指向的元素赋值 使用extend过程(或者trim进行压缩),没有预定义的最大值 extend(或trim),但是最大只能到声明的最大尺寸
可以比较相等与否 不可以 可以,要求是oracle10g或以后版本 不可以
是否通过集合操作符进行操作 不可以 可以,要求是oracle10g或以后版本 不可以
存取数据时是否会保留顺序或者下标 N/A 不保留 保留

下一篇会写写Spring如果将数组传人Oracle中

猜你喜欢

转载自chen3975.iteye.com/blog/1884829