在Pl / SQL中使用数组时,下标超出限制错误

时间:2014-04-17 10:25:25

标签: sql oracle

以下程序访问PL / SQL中的数组,但是当我执行该过程时,它会给我一个下标外部限制错误。为什么会这样?我没有看到这个程序有什么问题

CREATE OR REPLACE PROCEDURE ANALYSIS
IS
CURSOR EMPLOYEES IS
 SELECT * FROM EMPLOYEE;
CURSOR BILLS IS
 SELECT * FROM BILL;
WORKER EMPLOYEE%ROWTYPE;
CASH BILL%ROWTYPE;
TYPE SALARY IS VARRAY(4) OF NUMBER(5);
SALARIES SALARY;

BEGIN
 SALARIES:=SALARY(1,1,1,1);
 SALARIES.EXTEND(4);
 OPEN EMPLOYEES;
 OPEN BILLS;
 LOOP
  FETCH EMPLOYEES INTO WORKER;
  EXIT WHEN EMPLOYEES%NOTFOUND;
  IF WORKER.BRANCHID=1 THEN 
   SALARIES(1):=SALARIES(1)+WORKER.SALARY;
  ELSIF WORKER.BRANCHID=2 THEN 
   SALARIES(2):=SALARIES(2)+WORKER.SALARY;
  ELSIF WORKER.BRANCHID=3 THEN 
   SALARIES(3):=SALARIES(3)+WORKER.SALARY;
  ELSIF WORKER.BRANCHID=4 THEN 
   SALARIES(4):=SALARIES(4)+WORKER.SALARY;
  END IF;
 END LOOP;
END;

1 个答案:

答案 0 :(得分:3)

您已创建一个最多可包含4个元素的数组SALARY:

TYPE SALARY IS VARRAY(4) OF NUMBER(5);

然后你填充了4个元素:

SALARIES:=SALARY(1,1,1,1);

然后你试图用另外4个元素扩展它,即8个元素:

SALARIES.EXTEND(4);

这就是你得到错误的地方:

SQL> DECLARE
  2  TYPE SALARY IS VARRAY(4) OF NUMBER(5);
  3  SALARIES SALARY;
  4  BEGIN
  5   SALARIES:=SALARY(1,1,1,1);
  6   SALARIES.EXTEND(4);
  7  END;
  8  /
DECLARE
*
ERROR at line 1:
ORA-06532: Subscript outside of limit
ORA-06512: at line 6

您不需要EXTEND行。

NB其他几点:

  1. 由于您将数组值初始化为1,您的总数最终会比应该的数值高1?
  2. 为什么不选择BRANCHID,SUM(SALARY)而不是手动添加循环?