使用For循环在Oracle过程中检索多行

使用For循环在Oracle过程中检索多行,oracle,stored-procedures,join,plsql,cursor,Oracle,Stored Procedures,Join,Plsql,Cursor,我正在处理存储过程,我需要检索一组结果,分别处理每个元素,然后返回整个结果 我对数据库不太熟悉,但以下是我能想到的 create or replace procedure GET_EMP_RSLT IS CURSOR ecursor IS select emp_id from temp_employee where 'some condition'; BEGIN FOR empidset in ecursor LOOP Select * from (sele

我正在处理存储过程,我需要检索一组结果,分别处理每个元素,然后返回整个结果

我对数据库不太熟悉,但以下是我能想到的

create or replace procedure GET_EMP_RSLT
  IS

CURSOR ecursor IS select emp_id from temp_employee where 'some condition';

BEGIN

FOR empidset in ecursor  

  LOOP

  Select * from 

    (select * from payroll_info where emp_id = empidset.emp_id) a

    left join 

    (select * from benefit_info where emp_id = empidset.emp_id) b 
     on a.emp_id = b.emp_id    

  END LOOP;

END;
在执行时,我得到以下错误

an INTO clause is expected in this SELECT statement : "Select * from"
谁能解释一下我如何纠正这个错误并获得所需的结果

备注:我正在使用Oracle 9i和TOAD 9

谢谢,
Tom

您需要添加一个INTO子句来指定要放置所选数据的局部变量,例如

select ID, Name
  into myID, myName
from emp

循环中的SELECT内部需要有一个INTO子句来处理值——代码中不清楚您要做什么,但我怀疑游标循环中嵌套的SELECT/JOIN可以更好地编写为主游标中的三表联接。

下面是一个可能的解决方案,提出了许多假设。如前所述,它以包含所有3个表的数据的ref游标的形式返回结果。让它为每个表返回ref游标并不重要,但对于可疑的结果,这将是更多的工作

然而,除非您真的在PL/SQL中做一些在SQL中做不到的事情,否则直接在SQL中做这件事会更好

create object EMP_PAYROLL_BENEFIT as object (
   em_id number,
   some_payroll_column number,
   some_benefit_column number);

create type NT_EMP_PAYROLL_BENEFIT as table of EMP_PAYROLL_BENEFIT;

create or replace procedure GET_EMP_RSLT(p_output OUT sys_refcursor)  IS    
CURSOR ecursor IS select emp_id 
                  from temp_employee te 
                       join payroll_info pi 
                       on te.emp_id = pi.emp_id 
                       join benefit_info bi 
                       on te.emp_id = bi.emp_id 
                  where some_column = 'some condition';
v_results NT_EMP_PAYROLL_BENEFIT;
BEGIN
   open ecursor;
   fetch ecursor bulk collect into v_results;
   close ecursor;
   for i = v_results.first..v_results.last loop
      v_results.some_benefit_column := some_payroll_column + i;
   end loop;
   open p_output for select * from table(v_results);
end;

代码中有太多的语法和思想错误。 因此,请阅读,特别是为了理解SQL和PL/SQL之间的区别,通常是SQL查询语言、PL/SQL编程语言以及您案例中的章节:

和 和 有关Oracle 9i R2的完整PL/SQL参考,请访问


可以找到所有Oracle 9i R2文档集。

+1,特别是建议将所有选择移到主光标中。您关于INTO子句将解决此问题的建议假定循环中的select对于游标上的每次迭代只返回一行,否则会出现ORA-1422错误。假定select返回一行。