oracle游标的更新与删除数据

通过使用显示游标,不仅可以一行一行地处理SELECT语句的结果,而且也可以更新或删除当前游标行的数据。注意,如果要通过游标更新或删除数据,在定义游标时必须要带有FOR UPDATE 子句,语法如下:

cursor cursor_name is select ...for update;

在提取了游标数据之后,为了更新或删除当前游标行数据,必须在update或delete语句中引用where current of子句,语法如下:

update table_name set column=...where current of cursor_name;

delete table_name where current of cursor_name;

1.使用游标更新数据

下面以给工资低于2000的雇员增加100元工资为例,说明使用显示游标更新数据的方法。示例如下:
declare
cursor emp_cursor is 
select ename,sal from emp for update;
v_ename emp.ename%type;--定义变量
v_sal emp.sal%type;
begin
open emp_cursor;--打开游标
loop
fetch emp_cursor into v_ename,v_sal;--提取游标数据赋值给变量
exit when emp_cursor%notfound;
if v_sal <2000 then --当变量v_sal 小于2000时执行更新操作
update emp set sal=sal+100 where currentof emp_cursor;
end if ;
end loop;
close emp_cursor;--关闭游标
end;

2.使用游标删除数据

下面以解雇部门号为30的所有雇员为例,说明使用显示游标删除数据的方法,示例如下:
declare
cursor emp_cursor is 
select ename,sal ,deptno from emp for update;
v_ename emp.ename%type;--定义变量
v_sal emp.sal%type;
v_deptno emp.deptno%type;
begin
open emp_cursor;--打开游标
loop
fetch emp_cursor into v_ename,v_sal,v_deptno;--提取游标数据赋值给变量
exit when emp_cursor%notfound;
if v_deptno =30 then --当变量v_deptno等于30时执行删除操作
delete from  emp where current  of emp_cursor;
end if ;
end loop;
close emp_cursor;--关闭游标
end;
  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值