Oracle – ORA 06533: Subscript beyond count

oracleplsql

I created below simple block but getting

ORA 06533:Subscript beyond count

error.

Can someone please tell me what I am missing in below code.

declare
  type salaryvarray is varray(6) of customers.salary%type;
  salary_array salaryvarray:=salaryvarray();
  c_salary customers.salary%type;
  i integer(2);
  counter number(2);
begin
  salary_array.extend;
  select count(*) into counter from customers;
  for i in 1..counter loop
    select salary into c_salary from customers where id =i;
    salary_array(i):=c_salary;
  end loop;
end;
/

Best Solution

The array_var.extend portion of the code needs to be inside the loop. Each time you add to it, you are allocating new memory. Skipping this step is asking the code to store something without giving it space.

declare
  type salaryvarray is varray(6) of customers.salary%type;
  salary_array salaryvarray:=salaryvarray();
  c_salary customers.salary%type;
  i integer(2);
  counter number(2);
begin
  select count(*) into counter from customers;
  for i in 1..counter loop
    salary_array.extend; -- Extend for each value.
    select salary into c_salary from customers where id =i;
    salary_array(i):=c_salary;
  end loop;
end;
/

You will very likely run into a similar error soon, however, ORA-06532: Subscript outside of limit. You limit your VARRAY to 6 elements, but customers could potential have more. Consider limiting the return, expanding the VARRAY or implementing a more dynamic collection type.

Related Question