SQL-Oracle游标

6 篇文章 0 订阅
3 篇文章 0 订阅

游标提供了一种从集合性质的结果集中提供出单条记录的手段,初始时指向首记录。

  • 游标的种类
    静态游标、REF游标

    静态游标:可以理解为一个数据快照,打开游标后的结果集是数据库表中数据的备份,数据不会对表的DML操作而改变。

    ①显式静态游标:是指在使用之前必须有明确的游标定义,这种游标的定义会关联数据查询语句,通常会返回一行或多行,打开游标后可以利用游标的位置对结果集进行检索,使之返回单一的行记录,用户可以操作该记录,关闭游标后就不能对结果集进行操作。

    ②隐式静态游标:和显式游标不同,它被PL/SQL自动管理,也被称为SQL游标。

  • 显示游标的使用
    语法

cursor cursor_name[(parameter_name datatype,...)]
is 
    select_statement;
使用步骤:声明、打开、读取数据、关闭

①声明游标
declare cursor cursor_name is select_statement;
②打开游标(游标一旦被打开,结果就是静态的了)
open cursor_name;
③读取数据
读取数据要用到fetch,它可以吧游标指向位置的记录读取到pl/sql声明的变量中。
fetch cursor_name into record_name
④关闭游标
close cursor_name;

游标中简单的loop语句
eg:

declare
    cursor test_cursor is select * from test1;
    test_id  test1.id%type;
    test_name test1.name%type;
    test_money test1.money%type;

begin
    open test_cursor;
    loop
        fetch test_cursor into test_id,test_name,test_money;
        exit when test_cursor%notfound;
        dbms_output.put_line('.....');
    end loop;
    close test_cursor;
end;

需要注意的是:使用fetch…into..提取数据的时候的单条提取,数据量较大时效率比较低。

使用fetch…bulk collect into 提取大数据量的游标数据
eg:

declare
    cursor emp_cursor is 
       select * from emp;
    type emp_tab is table of emp%rowtype;
    emp_rd emp_tab;
begin
    open emp_cursor;
    loop
        fetch emp_cursor bulk collect into emp_rd limit 2;
        for i in 1...emp_rd.count
        loop
            dbms_output.put_line(......);
        end loop;
        exit when emp_cursor%notfound;
    end loop;
    close emp_cursor;
end;

利用cursor … for … loop 便利游标数据,使用简洁、方便
eg:

declare
    cursor test_cursor is
       select * from test1;
begin
    for rec in test_cursor
    loop
        dbsm_output.put_line(.....);
    end loop;
end;

带参数的游标
eg:

declare
    test_id1 test.id%type := 1;
    test_id2 test.id%type := 2;
    cd_test test1%rowtype;
    cursor test_cursor(id1 number,id2 number)
       is select * from test1 where id in(id1,id2);
begin
    open test_cursor(test_id1,test_id2);
    loop
        fetch test_cursor into cd_test;
        exit when test_cursor%notfound;
           dbsm_output.put_line(...);
    end loop;
    close test_cursor;
end;
  • 隐式游标
    隐式游标和显式游标有所差异,它显没有显式游标的课操作性,每当运行DQL或DML语句时,PL/SQL会打开一个隐式游标,隐式游标不受用户控制。
    ①隐式游标由pl/sql自动管理
    ②隐式游标的默认名称是SQL
    ③DQL和DML语句产出隐式游标
    ④隐式游标的属性值是指是最新执行的sql语句的。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值