Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning more than one column to a collection using BULK COLLECT

I am not sure why I am getting this error with this code, Please help me with debugging this code Thanks in advance.

declare
type emp_t is table of employees%rowtype
index by pls_integer;
rec   emp_t;
begin
  select employee_id,salary,manager_id bulk collect into rec
  from employees where rownum <100;

 forall i in 1..rec.last
    update employees
    set salary=salary+10
    where employee_id=rec(i).employee_id;

end;

ORA-06550: line 7, column 3:
PL/SQL: ORA-00913: too many values
ORA-06550: line 6, column 3:
PL/SQL: SQL Statement ignored
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

I have changed the code to the below format but it's still giving me "expression is of wrong type error"

declare 
type emp_t is table of employees%rowtype
index by pls_integer;
rec   emp_t;

begin
for val in (
  select employee_id,salary,manager_id 
  from employees where rownum <100)

  loop
      rec:=val;

  end loop;

 forall i in 1..rec.last
    update employees
    set salary=salary+10
    where employee_id=rec(i).employee_id;

end;
like image 609
redsoxlost Avatar asked Oct 20 '25 03:10

redsoxlost


1 Answers

Use either one or the other:

  TYPE emp_t IS TABLE OF employees%ROWTYPE INDEX BY PLS_INTEGER;
  --                     ^^^^^^^^^^^^^^^^^
  --                  each record is "one row" of table `employees`

  ...

  SELECT * BULK COLLECT INTO rec FROM employees WHERE ROWNUM < 100;
  --     ^
  --   get all columns for each row

Or

  TYPE emp_rec IS RECORD (
    employee_id employees.employee_id%TYPE,
    salary employees.salary%TYPE,
    manager_id employees.manager_id%TYPE
  );
  TYPE emp_t IS TABLE OF emp_rec
  --                     ^^^^^^^
  --               each record only contains the necessary fields

  ...

  SELECT employee_id,salary,manager_id BULK COLLECT INTO rec FROM employees WHERE ROWNUM < 100;
  --     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  --       get only what we need (and in that particular order)

Very probably you are looking for the second form. Using a custom type for the RECORD you are trying to bulk collect. Please notice the use of %TYPE attribute in the record declaration. That's an alias to the type of each column.

like image 79
Sylvain Leroux Avatar answered Oct 24 '25 07:10

Sylvain Leroux