Search code examples
plsqlvarray

Collections not working in PLSQL


By below code is not working for cursor on PLSQL. I receive an error message.


 declare 
      type abc is varray(10) of number;
      cursor x is select Empno from emp where rownum <10;
      a abc;
      counter  number :=1;
    begin
      a:=abc();
     for i in x
     loop
      a.extend();
      a(i):=counter.Empno;
      DBMS_output.put_line(a(i));
      counter:=  end loop;
    end;

Solution

  • You have used counter instead of for loop iterator i:

    Try;

    declare 
        type abc is varray(10) of number;
        cursor x is select Empno from emp where rownum <10;
        a abc;
        counter number := 1;
    begin
        a:=abc();
        for i in x loop
            a.extend();
            a(counter) := i.Empno;
            DBMS_output.put_line(a(counter));
            counter := counter + 1;
        end loop;
    end;
    

    Or you can use Bulk collect to insert data into varray

    declare 
        type abc is varray(10) of number;
        a abc := abc();        
    begin  
        select Empno BULK COLLECT INTO a from emp where rownum <10;
        for i in 1 .. a.count loop 
            DBMS_output.put_line(a(i)); 
        end loop;
    end;