使用BULK COLLECT为集合分配多个列

时间:2014-09-28 17:15:28

标签: oracle plsql

我不知道为什么我这个代码会出现此错误,请提前帮助我调试此代码。

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:

我已将代码更改为以下格式,但它仍然给我&#34;表达式错误类型错误&#34;

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;

2 个答案:

答案 0 :(得分:5)

使用其中一个:

  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

  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)

很可能你正在寻找第二种形式。使用正在尝试批量收集的custom type for the RECORD。请注意在记录声明中使用%TYPE attribute。这是每列类型的别名。

答案 1 :(得分:0)

emp_t声明为ROWTYPE,其中包含所有列,
但在检索记录时,您只检索employee_id,salary,manager_id, 这可能是你错误的原因。

试试这个:

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;

第二个似乎有其他问题,如TYPE差异VAR和REC