首页 > 解决方案 > PL/SQL 错误引用未初始化的集合错误,即使它已初始化

问题描述

我有一个使用嵌套表的 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:引用未初始化的集合。请帮我调试这个。

标签: oracleplsql

解决方案


如果您发布完整的(示例)代码(而不是“...”)会有所帮助。

这是一个基于 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.

推荐阅读