• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Oracle游标使用

武飞扬头像
叶涛网站推广优化
帮助1

Oracle游标的本质是一个结果集resultset,主要用来临时存储从数据库中提取出来的数据块。游标的分类:

1、显式游标:由用户定义,需要的操作:定义游标、打开游标、提取数据、关闭游标,主要用于对查询语句的处理。

一、Oracle游标使用游标

对于DML语句和单行select into ,oracle自动分配隐形游标。处理select返回多行语句,可以使用显式游标。

使用显示游标处理多行数据,也可使用SELECT..BULK COLLECT INTO 语句处理多行数据.

1.Oracle游标定义游标

cursor cursor_name is select_statement;

2.Oracle游标打开游标

执行对应的SELECT语句并将SELECT语句的结果暂时存放到结果集中.

open cursor_name;

3.Oracle游标提取数据

打开游标后,SELECT语句的结果被临时存放到游标结果集中,使用FETCH语句只能提取一行数据

通过使用FETCH..BULK COLLECT INTO语句每次可以提取多行数据

1

2

3

fetch cursor_name into variable1,varibale2,...;

fetch cursor_name bulk collect into collect1,collect2,...[limit rows];

(1)游标中使用fetch..into语句:只能处理一行数据,除非用循环语句

1

2

3

4

5

6

7

8

9

10

11

12

declare

v_bookname varchar2(100);

cursor c_book(i_id number) is select bookname from book where id = i_id;

begin

Open c_book(10);--打开游标

Loop

Fetch c_book into v_bookname; --提取游标

exit when c_book%notfound;

update book set price = '33' where bookname = v_bookname;

End Loop;

Close c_book;--关闭游标

end;

1

2

3

4

5

6

7

8

9

10

11

12

declare

v_bookname varchar2(100);

cursor c_book(i_id number) is select bookname from book where id = i_id;

begin

Open c_book(10);

Fetch c_book into v_bookname;--预先Fetch一次

While c_book%found Loop

update book set price = '33' where bookname = v_bookname;

Fetch c_book into v_bookname;

End Loop;

Close c_book;

end;

(3)基于游标定义记录变量

1

2

3

4

5

6

7

8

9

10

11

declare

cursor emp_cursor is select ename,sal from emp;

emp_record emp_cursor%rowtype;

begin

open emp_cursor;

loop

fetch emp_cursor into emp_record;

exit when emp_cursor%notfound;

dbms_output.put_line('雇员名:'||emp_record.ename||',雇员工资:'||emp_record.sal);

end loop;

end;

4.关闭游标

1

close cursor_name;

5.游标属性

用于返回显示游标的执行信息,包括%isopen,%found,%notfound,%rowcount

  • %isopen:确定游标是否打开

  • %found:检查是否从结果集中提取到了数据

  • %notfound:与%found行为相反。

  • %rowcount:返回当前行为止已经提取到的实际行数

no_data_found和%notfound的用法是有区别的,小结如下1)SELECT. . . INTO 语句触发 no_data_found;

2)当一个显式光标(静态和动态)的 where 子句未找到时触发 %notfound;

3)当UPDATE或DELETE语句的where 子句未找到时触发 sql%notfound;

4)在光标的提取(Fetch)循环中要用 %notfound 或%found 来确定循环的退出条件,不要用no_data_found。

6.参数游标

注意:定义参数游标时,游标参数只能指定数据类型,而不能指定长度。

1

2

3

4

5

6

7

8

9

10

11

12

declare

cursor emp_cursor(no number) is select ename from emp where deptno=no;

v_ename emp.ename%type;

begin

open emp_cursor(10);

loop

fetch emp_cursor into v_ename;

exit when emp_cursor%notfound;

dbms_output.put_line(v_ename);

end loop;

close emp_cursor;

end;

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhhhhifa
系列文章
更多 icon
同类精品
更多 icon
继续加载