How to store selection result in to variable in Oracle procedure

我的未来我决定 提交于 2019-12-20 20:40:15

问题


I write a simple procedure. I try to store selection result in variable. I use "SELECT INTO" query but I can not doing this.

Example:

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

回答1:


You have a couple options. You could turn that query into a cursor:

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;

Or, you can create a TABLE variable:

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;

I haven't tried these samples in Oracle, so you may get compiler errors...




回答2:


IF your SELECT returns more than one row, you won't be able to use the SELECT INTO synthax.

You will need to build a loop to navigate through the resulte set:

Adam demonstrated how you would use an explicit cursor and a bulk collect loop. I will show how you can build the simplest loop possible (implicit cursor, doesn't need a DECLARE section):

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;


来源:https://stackoverflow.com/questions/1347091/how-to-store-selection-result-in-to-variable-in-oracle-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!