您的位置:首页 > 数据库 > Oracle

oracle游标的更新与删除数据

2015-08-25 14:48 537 查看
通过使用显示游标,不仅可以一行一行地处理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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: