Updating database records in a loop?

前端 未结 6 812
轮回少年
轮回少年 2021-02-10 09:19
declare
begin
  for i in (select * from emp)
  loop
    if i.sal=1300 then
      update emp
      set sal=13000;
    end if;
  end loop;
end;

This code

6条回答
  •  眼角桃花
    2021-02-10 09:46

    Whenever you can do the update with one single statement, you should do that instead of using a loop. You'll get a very huge performance gain that way; or, the other way round, updates in a loop cost you a lot of performance.

    If you really really have to use a loop, of course you need a where condition to make sure you are only updating the record you really want to update. A possible way that always works (even if there is no unique key available) is to use the rowid pseudocolumn:

    begin
      for i in (select rowid, emp.* from emp)
      loop
        if i.sal=1300 then
          update emp
          set sal=13000
          where rowid=i.rowid;
        end if;
      end loop;
    end;
    

    Another possibility would be using an explicit cursor and the "update ... where current of cursorname" syntax.

提交回复
热议问题