循环遍历Oracle列的值

时间:2014-11-10 13:24:41

标签: oracle loops

我有一个非常基本的PL / SQL问题。

如何循环某个表列的值并更新它们?

我是在循环中这样做吗?

1 个答案:

答案 0 :(得分:0)

通常不需要遍历表格。您所要做的就是执行那种

的更新声明
 UPDATE mytable
 SET    myfield = 'new value'
 WHERE  somecondition;

但您也可以定义游标以进行更新。 Google for" oracle游标循环更新当前"。一个例子是http://www.techonthenet.com/oracle/cursors/current_of.php

这是我自己的例子:

create table my_example(id number, somefield varchar2(80));
insert into my_example values (1, 'test 1');
insert into my_example values (2, 'test 2');
insert into my_example values (3, 'test 3');
set linesize 100
select * from my_example;

set serveroutput on
declare
  l_somefield varchar2(80);
  cursor c is select somefield from my_example for update of somefield; 
begin
  open c;
  loop
    fetch c into l_somefield;
    exit when c%notfound;
    update my_example
    set somefield = l_somefield || ' some more text'
    where current of c;
  end loop;
  close c;
end;

select * from my_example;
drop table my_example;

输出

Table created.
1 row created.
1 row created.
1 row created.

        ID SOMEFIELD                                                                       
---------- --------------------------------------------------------------------------------
         1 test 1                                                                          
         2 test 2                                                                          
         3 test 3                                                                          

3 rows selected.
PL/SQL procedure successfully completed.

        ID SOMEFIELD                                                                       
---------- --------------------------------------------------------------------------------
         1 test 1 some more text                                                           
         2 test 2 some more text                                                           
         3 test 3 some more text                                                           

3 rows selected.
Table dropped.