集合方法
pl/sql预定义了在varray 和嵌套表实例上进行调用的方法。这些方法能在集合上执行一定的功能。
EXISTS | 该函数返回集合中第一个元素的索引,如果集合为空,返回NULL | Collection.EXISTS(index) |
COUNT | 该函数集合元素的数目 | Collection.COUNT |
DELETE | 该过程从嵌套表中删除一个或多个或合部元素 | Table_name.DELETE 删除所有元素 Table_name.delete(index)删除指定索引的记录 Table_name.delete(start_index,end_index)删除区间内元素 |
FIRST | 返回集合第一个元素索引,如果集合为空,返回NULL | Collection.FIRST 注意(与插入顺序无关,基于下标的数字或字符串升序排序后,去第一个为first,取最后一个为last) |
LAST | 返回集合中最后一个元素索引,如果集合为空,返回NULL | Collection. LAST |
NEXT | 返回集合当前元素的下一个元素的索引,如果它不存在就返回NULL | Collection. NEXT |
PRIOR | 返回集合当前元素的上一个元素的索引,如果它不存在就返回NULL | Collection. PRIOR |
LIMIT | 返回varray中创建元素的最大个数 | Collection. LIMIT |
EXTENDS | 该过程在集合的末尾添加新的元素 | Collection.EXTEND添加一个NULL元素;Collection.extends(n)添加N个NULL元素,Collection.extend(n,index)添加由index指定位置上元素的n个副表 |
TRIM | 从集合末尾处删除元素 | Collection.TRIM 删除最后一个元素 Collection.TRIM(n)删除最后N个元素 |
另外,集合可以用类型type加小括号进行初始化如:
create or replace type table_type is table of number;
v_table table_type;
v_table := table_type();
例子如下(类似system_config表):
declare
TYPE t_tab IS TABLE OF NUMBER INDEX BY varchar2(10);
v_tab t_tab;
begin
-- Test statements here
FOR i IN 1..10 LOOP
v_tab(i||'a') := i;
END LOOP;
FOR i IN 1..10 LOOP
dbms_output.put_line('第'||i||'a'||'个元素为'||v_tab(i||'a'));
END LOOP;
v_tab.DELETE;
/* v_tab.DELETE(9||'a');
dbms_output.put_line('delete 第'||9||'a');*/
/* v_tab.DELETE(10||'a');
dbms_output.put_line('delete 第'||10||'a');*/
/* v_tab.DELETE(5||'a');
dbms_output.put_line('delete 第'||5||'a');*/
dbms_output.put_line(to_char(v_tab.COUNT) ||' count.');
dbms_output.put_line(to_char(v_tab.FIRST) ||' first.');
dbms_output.put_line(to_char(v_tab.LAST) ||' last.');
end;
-- Created on 2010/1/3 by DUQIANG 关于count,first,last,next等的使用index by table
declare
type t_student_tab is table of student%rowtype index by binary_integer;
v_student_tab t_student_tab;
v_first number;
v_last number;
v_count number;
v_index number;
begin
for i in reverse 1..5 loop --insert
select * into v_student_tab(i) from student where cn= i;
end loop;
v_student_tab.delete(1);
v_first := v_student_tab.first;
v_last := v_student_tab.last;
v_count := v_student_tab.count;
v_index := v_student_tab.first;
while v_index <= v_student_tab.last loop
dbms_output.put('element '||v_index||':');
dbms_output.put_line(v_student_tab(v_index).cn||';');
v_index := v_student_tab.next(v_index);
end loop;
dbms_output.put_line('fisrt:'||v_first);
dbms_output.put_line('last:'||v_last);
dbms_output.put_line('count:'||v_count);
exception
when no_data_found then dbms_output.put_line('no_data_found exception raised!');
end;