如何将选择结果存储到Oracle过程中的变量中

时间:2009-08-28 13:46:29

标签: oracle stored-procedures select-into

我写了一个简单的程序。我尝试将选择结果存储在变量中。我使用“SELECT INTO”查询,但我不能这样做。

示例:

DECLARE
     v_employeeRecord  employee%ROWTYPE;
BEGIN
 SELECT * INTO v_employeeRecord
      FROM Employee WHERE Salary > 10;
END;

2 个答案:

答案 0 :(得分:13)

你有几个选择。您可以将该查询转换为游标:

DECLARE
     CURSOR v_employeeRecords IS
          SELECT * FROM Employee WHERE Salary > 10;
     v_employeeRecord  employee%ROWTYPE;
BEGIN
     FOR v_employeeRecord IN v_employeeRecords LOOP
          /* Do something with v_employeeRecord */
     END LOOP;
END;

或者,您可以创建TABLE变量:

DECLARE
     v_employeeRecord  employee%ROWTYPE;
     v_employeeRecords IS TABLE OF employee%ROWTYPE;
     i BINARY_INTEGER;
BEGIN
 SELECT * BULK COLLECT INTO v_employeeRecords
      FROM Employee WHERE Salary > 10;

 i := v_employeeRecords.FIRST;
 WHILE v_employeeRecords.EXISTS(i) LOOP
     v_employeeRecord := v_employeeRecords(i);
     /* Do something with v_employeeRecord */
     i := v_employeeRecords.NEXT(i);
 END;
END;

我没有在Oracle中尝试过这些示例,因此您可能会遇到编译错误......

答案 1 :(得分:8)

如果您的SELECT返回多行,您将无法使用SELECT INTO synthax。

您需要构建一个循环来导航结果集:

Adam演示了如何使用显式游标和批量收集循环。我将展示如何构建最简单的循环(隐式游标,不需要DECLARE部分):

BEGIN
   FOR c_emp IN (SELECT * 
                   FROM Employee 
                  WHERE Salary > 10) LOOP
      /* do something with each row, for example:*/
      UPDATE foo SET bar = bar + c_emp.salary WHERE id = c_emp.id;
   END LOOP;
END;