且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

循环更新数据库记录吗?

更新时间:2023-02-08 16:30:11

只要您可以使用一条语句进行更新,就应该这样做,而不要使用循环.这样,您将获得非常巨大的性能提升.或者反之,循环更新会花费很多性能.

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.

如果确实需要使用循环,那么当然需要一个where条件,以确保仅更新您真正想要更新的记录.始终有效的一种可能方法(即使没有可用的唯一键)是使用rowid伪列:

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;

另一种可能性是使用显式游标和更新...此处为 cursorname 的最新版本"语法.

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