Oracle更新的多种场景

Oracle更新的多种场景。

1、按照条件更新已知字符串(此方法适用于少量数据的更新),实例如下:

update ywgl_newsclass set newclassname = 
    case
      when id=1 then '要事公告'
      when id=2 then '林业产品'
      when id=3 then '劳务服务'
      when id=4 then '林业协会'
      when id=5 then '林产企业'
      when id=6 then '合作交流'
    end
where id in (1,2,3,4,5,6);
commit;

说明:更新速度可以,缺点为只适用于少量数据,十条数据以内为佳。

2、将一个表中的某些字段值更新到另一个表中的字段中,实例如下:

update ywgl_user u set u.userId=(select userId from Department d where d.userId=d.userId)
where exists (select 1 from ywgl_roles r where r.id=u.userId)

说明:此方法为传统的更新语法,速度较下面几种语法语句而言,应该是最慢的,不过这种写法使用最广泛。

或者用Merge方法进行更新,如下所示:

merge into ywgl_user u
using(select userId from ywgl_department)  d on u.userID=d.userId
when matched then
   update set u.userName=d.userName
when not matched then
   insert into u (u.userName) values(d.userName);
commit;

说明:次语法适用于关键字段非主键时,优点为速度较快,能处理大量数据。

3、若需要按照某个顺序或者条件依次更新某些字段,则可以使用for语句进行更新:

begin
for x in REVERSE 1..10  loop  --REVERSE 有大到小排列
update ywgl_user u set userId=x where exists (select 1 from ywgl_roles r where r.id=u.userId) ; --更新语句
end loop;  --结束循环
end;

或者如下方法实现:

begin
for x in (select a.rowid as rowid,b.state as state from ywgl_user a,ywgl_roles b
where a.userId=b.Id ) loop
update ywgl_department set userState=x.state
where rowid=x.rowid;
end loop;
end;

说明:此种写法比较含蓄,没有定义游标进行储存变量x,而是以隐形的方式将游标运用于for循环中,进行了快速的定位并更新。

优点为:更新效率高。

缺点为:不返回影响行数。

(0)
上一篇 2022年3月22日
下一篇 2022年3月22日

相关推荐