Index by 表集合的 first last 属性

例:

declare

type list_of_names is table of scott.emp.ename%type index by binary_integer;

s_name list_of_names;

l_row binary_integer;

begin

s_name(11):='a1';

s_name(2):='a2';

s_name(3):='a3';

s_name(4):='a4';

s_name(7):='a7';

   

FOR l_row IN s_name.first .. s_name.last LOOP

dbms_output.put_line(l_row);

END LOOP;

end;

上面的输出结果如下:

2

3

4

5

6

7

8

9

10

11

   

从结果上,我们可以看出,如果用for .. In 语句来遍历index by 表集合的话,那么这个集合的下标会从最小连续到最大,当输出没有下标的元素时就会报错:

   

declare

type list_of_names is table of scott.emp.ename%type index by binary_integer;

s_name list_of_names;

l_row binary_integer;

begin

s_name(11):='a1';

s_name(2):='a2';

s_name(3):='a3';

s_name(4):='a4';

s_name(7):='a7';

   

FOR l_row IN s_name.first .. s_name.last LOOP

dbms_output.put_line(l_row);

dbms_output.put_line('the name is '||s_name(l_row));

END LOOP;

end;

上面的输出结果如下:

2

the name is a2

3

the name is a3

4

the name is a4

5

并伴有报错信息:

这个错误是因为在查询下标为5的元素时,不存在下标为5的元素,所以报错。

   

我们可以用下面的方法改进这个功能:

declare

type list_of_names is table of scott.emp.ename%type index by binary_integer;

s_name list_of_names;

l_row binary_integer;

begin

s_name(11):='a1';

s_name(2):='a2';

s_name(3):='a3';

s_name(4):='a4';

s_name(7):='a7';

l_row:=s_name.first;--first无参,可以不需要括号

--循环迭代数据

while (l_row is not null) loop

dbms_output.put_line('the name is '||s_name(l_row)||' 下标是:'||l_row);

l_row:=s_name.next(l_row);--next(x),返回下一个下标

end loop;

end;

输出结果:

the name is a2 下标是:2

the name is a3 下标是:3

the name is a4 下标是:4

the name is a7 下标是:7

the name is a1 下标是:11

   

用 集合的.next(下标)可以获得集合的下一个不连续的下标值。从而可以避免连续。

   

   

posted @ 2013-09-24 15:16  -Bill  阅读(310)  评论(0编辑  收藏  举报