游标 是从表中检索出结果集,从中每次指向一条记录进行交互的机制。
作用
指定结果集中特定行的位置。 基于当前的结果集位置检索一行或连续的几行。 在结果集的当前位置修改行中的数据。 对其他用户所做的数据更改定义不同的敏感性级别。 可以以编程的方式访问数据库。一个简单实用:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Declare -- 声明游标 Cursor Mycur Is Select * From Emp; Empinfo Emp%Rowtype; Cou Number; Begin -- 游标操作使用循环,但是在操作之前必须先将游标打开 For Empinfo In Mycur Loop Cou := Mycur%Rowcount; Dbms_Output.Put_Line( '行号:' || Cou || ' 雇员编号:' || Empinfo.Empno || ' 雇员姓名:' || Empinfo.Ename); End Loop; End ; |
循环取出数据的两种写法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
Declare -- 声明游标 Cursor Mycur Is Select * From Emp; -- List (EmpPo) Empinfo Emp%Rowtype; Cou Number; Begin -- 游标操作使用循环,但是在操作之前必须先将游标打开 If Mycur%Isopen Then Null ; Else Open Mycur; End If; -- 使游标向下一行 Fetch Mycur Into Empinfo; -- 判断此行是否有数据被发现 While (Mycur%Found) Loop Cou := Mycur%Rowcount; Dbms_Output.Put_Line( '行号:' || Cou || ' 雇员编号:' || Empinfo.Empno || ' 雇员姓名:' || Empinfo.Ename); -- 修改游标,继续向下 Fetch Mycur Into Empinfo; End Loop; End ; |
第二种写法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
Declare -- 声明游标 Cursor Mycur Is Select * From Emp; Empinfo Emp%Rowtype; Cou Number; Begin -- 游标操作使用循环,但是在操作之前必须先将游标打开 If Mycur%Isopen Then Null ; Else Open Mycur; End If; Loop -- 使游标向下一行 Fetch Mycur Into Empinfo; Exit When Mycur%Notfound; Cou := Mycur%Rowcount; Dbms_Output.Put_Line( '行号:' || Cou || ' 雇员编号:' || Empinfo.Empno || ' 雇员姓名:' || Empinfo.Ename); End Loop; End ; |
在存储过程中使用游标
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
Create Or Replace Procedure Myproc(Oi_Return Out Integer ) Is Cursor Mycur Is Select * From Emp_0915; Empinfo Emp_0915%Rowtype; Cou Number; Exc_Return Exception; -- 程序中间返回自定义异常 Begin If Mycur%Isopen Then Null ; Else Open Mycur; End If; Loop Fetch Mycur Into Empinfo; Exit When Mycur%Notfound; Cou := Mycur%Rowcount; Dbms_Output.Put_Line(Cou || '开始更新...' ); Update Emp_0915 t Set t.Sal = t.Sal + 1 Where t.Empno = Empinfo.Empno; Dbms_Output.Put_Line(Cou || '更新结束...' ); End Loop; Commit ; Oi_Return := 1; Exception When Exc_Return Then Rollback ; Oi_Return := 0; End ; |
在oracle中测试:
1 2 3 4 5 6 7 8 9 10 |
Declare Re Integer ; Begin Myproc(Re); If Re = 1 Then Dbms_Output.Put_Line(Re || ':执行结束。。。' ); Else Dbms_Output.Put_Line(Re || ':执行错误_______' ); End If; End ; |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.iteye.com/blog/cuisuqiang-756360
查看更多关于Oracle游标使用参考语句实例解析的详细内容...