当前提升和无效的rowid错误的当前

时间:2014-05-21 11:42:01

标签: oracle plsql cursor

我试图将每位顾客的年龄提高1并展示出来;使用游标。

这是表结构。

Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |

这是我的代码:

DECLARE
   c_id customers.id%TYPE;
   c_name customers.name%TYPE;
   c_age customers.age%TYPE;

   CURSOR c1 IS
    SELECT id, name, age
      FROM customers
       FOR UPDATE OF salary;
BEGIN
   OPEN c1;
   LOOP
       FETCH c1 INTO c_id, c_name, c_age;
       UPDATE customers
       SET age = age + 1
       WHERE CURRENT OF c1;

       EXIT WHEN c1%NOTFOUND;
       dbms_output.put_line( c_id || ' ' || c_name || ' ' || c_age );
   END LOOP;
   CLOSE c1;
END;
/

但是,我收到以下错误:

Error report:
ORA-01410: invalid ROWID
ORA-06512: at line 13
01410. 00000 -  "invalid ROWID"
*Cause:    
*Action:
1 Ramesh 32
2 Khilan 25
3 kaushik 23
4 Chaitali 25
5 Hardik 27
6 Komal 22

为什么会发生这种情况?如何阻止它?

1 个答案:

答案 0 :(得分:4)

你的exit在错误的地方;它应该在fetch之后直接。您正在正确处理六个实际行,但之后您将进行第七次获取 - 之后%notfound将为true - 因此没有“当前”行要更新。在尝试对该无效行执行任何操作之前,您需要退出。

BEGIN
   OPEN c1;
   LOOP
       FETCH c1 INTO c_id, c_name, c_age;
       EXIT WHEN c1%NOTFOUND;

       UPDATE customers
       SET age = age + 1
       WHERE CURRENT OF c1;

       dbms_output.put_line( c_id || ' ' || c_name || ' ' || c_age );
   END LOOP;
   CLOSE c1;
END;

希望这只是一个练习,因为它不是一种非常有效的更新方式。