我有一个使用嵌套表的PL/SQL脚本。下面是示例代码。
type rec is record
(
--col data types here
)
type rec_table is table of rec;
v_rec_table rec_table := rec_table(); --initialising here.
arr_size integer := 0; --edit 1
...
...
begin
...
...
open cursor;
loop
fetch cursor bulk collect into v_rec_table limit arr_size; --edit
if nvl(v_rec_table.last,0) > 0 --it shows error is here.
then
...
...
end if;
错误为 ORA-06531:引用未初始化的集合。请帮我调试这个。
如果您发布完整的(示例(代码(而不是"..."(,会有所帮助。
这是一个基于 Scott 模式的示例,该模式工作正常(您的错误行是第 14 行(:
SQL> declare
2 type rec is record (id number);
3 type rec_table is table of rec;
4 v_rec_table rec_table := rec_table();
5
6 cursor c1 is select empno from emp;
7 begin
8 open c1;
9 loop
10 exit when c1%notfound;
11 fetch c1 bulk collect into v_rec_table;
12 end loop;
13 dbms_output.put_line('last = ' || v_rec_table.last);
14 if nvl(v_rec_table.last, 0) > 0 then
15 dbms_output.put_line('last exists');
16 end if;
17 close c1;
18 end;
19 /
last = 12
last exists
PL/SQL procedure successfully completed.
不过,我不确定 LOOP 的用途是什么,因为您可以这样做
SQL> declare
2 type rec is record (id number);
3 type rec_table is table of rec;
4 v_rec_table rec_table := rec_table();
5 begin
6 select empno bulk collect into v_rec_table from emp;
7 dbms_output.put_line('last = ' || v_rec_table.last);
8 end;
9 /
last = 12
PL/SQL procedure successfully completed.
虽然你的问题不可重现,但我发现你的代码中几乎没有可以改进的地方。
如果您使用的是bulk collect
,则集合会自动初始化,因此不需要此行
v_rec_table rec_table := rec_table();
此外,如@Littlefoot所述,除非您使用LIMIT
子句,否则不需要LOOP
。
您可以使用COUNT
收集功能代替nvl(v_rec_table.last,0)
v_rec_table.count
您可以定义一个cursor%ROWTYPE
集合,而不是定义记录类型并批量收集到其中;
CURSOR cur is SELECT column1,column2 FROM tablename;
type rec_table is table of cur%ROWTYPE;
v_rec_table rec_table;
抱歉,因为我没有发布整个代码。发生此错误的原因是我没有将index by
添加到记录定义中的两列。
在阅读了几篇文章后,我发现了自己的缺陷。