使用游标填充记录类型

时间:2013-02-05 07:12:57

标签: oracle plsql oracle11g

我正在尝试从我的数据库中获取数据,但我在代码中找不到错误:

declare
  cursor c1 is select * from(select d.department_ID, d.department_name,count(d.department_name) cnt from emp e,dept d where e.department_id=d.department_id group by d.department_ID, d.department_name) where cnt>=5;
  TYPE cust_dept IS RECORD(dept_id dept.department_id%type,dept_name dept.department_name%type,emp_name emp.first_name%type);

begin 

FOR i IN c1
loop

    select * into cust_dept  from emp e, dept d where d.department_ID=i.department_ID;

 DBMS_OUTPUT.put_line('Department_id :'||i.department_id||' '||'department_name :'||i.department_name);--||' '||'customer_name :'||cust_dept.emp_name);
    --FETCH customer_cur into customer_rec;
    --EXIT WHEN customer_cur%notfound;
    --DBMS_OUTPUT.put_line(i.department_id);

 END LOOP;

end;
/

错误是:

ORA-06550: line 10, column 23:
PLS-00321: expression 'CUST_DEPT' is inappropriate as the left hand side of an assignment statement
ORA-06550: line 10, column 34:
PL/SQL: ORA-00904: : invalid identifier
ORA-06550: line 10, column 9:
PL/SQL: SQL Statement ignored
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

2 个答案:

答案 0 :(得分:1)

您的代码有几个问题

  1. cust_dept是一个类型,而不是声明变量的变量 输入cust_dept你需要这样的东西:cust_dept_var cust_dept;
  2. cust_dept变量的定义不会解决您的问题     问题因为select * from emp e, dept d where d.department_ID = i.department_ID可能无法返回单个答案,     可能有2个或更多或非结果所以基本上你需要定义     一个数组变量cust_dept
  3. 要获得您需要的结果,您可以使用下面的代码,您不需要定义记录类型,否则:

    begin
    for x in
    (select d.department_ID, d.department_name from emp e, dept d where e.department_id = d.department_id group by d.department_ID, d.department_name having count(d.department_name) >= 5) loop

    for y in (select e.department_id, d.department_name from emp e, dept d where d.department_ID = x.department_ID) loop DBMS_OUTPUT.put_line('Department_id :' || y.department_id || ' ' || 'department_name :' || y.department_name);
    end loop;
    end loop;
    end;

  4. 祝你好运;)

答案 1 :(得分:0)

您应该声明cust_dept类型的变量并选择它。