隐式游标demo:
给所有雇员加薪1000,使用隐式游标获取相关属性。
begin
update emp set sal=sal+1000;
dbms_output.put_line('影响行数:'||(sql%rowcount));
if not sql%isopen then
dbms_output.put_line('游标状态:关闭');
end if;
end;
知识点:
SQL%FOUND – SQL 语句影响了一行或多行时为 TRUE
SQL%NOTFOUND – SQL 语句没有影响任何行时为TRUE
SQL%ROWCOUNT – SQL 语句影响的行数
SQL%ISOPEN - 游标是否打开,始终为FALSE
显示游标DEMO:
使用显示游标给不同部门的雇员加薪:编号为10的加1000,编号为20的加2000,编号为30的加3000。
declare
cursor emp_cur is select * from emp where deptno =10 or deptno =20 or deptno =30 for update;
v_emp_row emp%rowtype;
begin
open emp_cur;--打开游标
loop
fetch emp_cur into v_emp_row;--每次取一行放在行变量里
exit when emp_cur%notfound;--当语句没有影响任何行数的时候
if v_emp_row.deptno=10 then--当部门编号为10的时候
update emp set sal=sal+1000 where current of emp_cur;--注意要制定当前行
end if;
if v_emp_row.deptno=20 then--当部门编号为20的时候
update emp set sal=sal+2000 where current of emp_cur;
end if;
if v_emp_row.deptno=30 then--当部门编号为30的时候
update emp set sal=sal+3000 where current of emp_cur;
end if;
end loop;
close emp_cur;--关闭游标
end;
将上面的显示游标改成for循环游标:
declare
cursor emp_cur is select * from emp where deptno =10 or deptno =20 or deptno =30 for update;
begin
for v_emp_row in emp_cur
loop
if v_emp_row.deptno=10 then
update emp set sal=sal+1000 where current of emp_cur;
end if;
if v_emp_row.deptno=20 then
update emp set sal=sal+2000 where current of emp_cur;
end if;
if v_emp_row.deptno=30 then
update emp set sal=sal+3000 where current of emp_cur;
end if;
end loop;
end;
注意:不用声明行变量,也不用开启游标,也不用关闭游标。方便至极。
使用ref游标查询特定雇员名及薪水,还有部门的地址:
declare
type ref_cur is ref cursor;
emp_cur ref_cur;
v_emp_row emp%rowtype;
v_empno emp.empno%type;
v_dept_address dept.loc%type;
v_dept_row dept%rowtype;
begin
v_empno:=&empno;
open emp_cur for 'select * from emp where empno=:1' using v_empno;
fetch emp_cur into v_emp_row;
close emp_cur;
open emp_cur for 'select * from dept where deptno=:1' using v_emp_row.deptno;
fetch emp_cur into v_dept_row;
close emp_cur;
dbms_output.put_line('雇员号:'||v_emp_row.empno||'雇员名:'||v_emp_row.ename||'部门地址'||v_dept_row.loc);
end;
游标的优点:
在缓存中修改,一次性提交
先查出数据并锁定,不会出现并发访问问题
游标的缺点:
并发可能性比较大的情况会降低性能
静态游标:关联SQL语句运行前就指定好了
动态游标:关联SQL语句在运行时指定
最主要目的:逐行进行不同处理,在缓存中修改,一次性提交。
显示管理游标的步骤:
1,声明游标,2,打开游标,3,从游标中读取数据,4,关闭游标
分享到:
相关推荐
ORACLE 游标使用示例,给大家可以共享一下。
Oracle游标使用大全 适合初学者,非常不错.PDF
Oracle游标使用方法及语法大全
oracle游标使用大全,详细描述了如何使用游标,创建游标等等
Oracle游标使用方法及语法大全.doc
oracle游标使用大全,其中有很多例子,有助于大家理解,希望对初学者有帮助
Oracle入门--Oracle游标使用! 值得下载看看!资源免费,大家分享!!
Oracle 游标使用大全
Oracle 游标使用大全.txt Oracle 游标使用大全.txt
详细的oracle游标用法,简单易懂,是学习游标的好材料
Oracle游标使用
详细介绍了 oracle的游标使用 及 实例
Oracle 游标使用大全 游标的定义使用 比较全的资料哦