Oracle:PL*SQL编程(二)---游标

本文详细介绍了如何使用游标来处理数据库查询结果。包括声明变量、声明游标、打开及关闭游标等步骤,并展示了游标与for循环结合使用的示例。此外还介绍了OPEN-FOR语句和无约束游标的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

游标(cursor)

可以使用游标获取查询返回的行。在通过查询将行检索到游标中后,可以一次从游标中取出一行。

1.步骤

使用游标遵循下面5个步骤:

步骤1:声明用于保存列值的变量

注意:这些变量必须与列的类型兼容。
例如:

declare
v_id test.id%TYPE;
v_type test.type%TYPE;
步骤2:声明游标

由游标名和希望执行的查询组成。

例如:

cursor v_test_cursor is
select id,type
from test;
步骤3:打开游标
open v_test_cursor;
步骤4:从游标中取得行

使用fetch:将列的值读取到在第1步声明的变量中。
例如:

将列的值读取到在第1步声明创建的v_id和v_type中。

fetch v_test_cursor
into v_id,v_type
步骤5:关闭游标
close v_test_cursor;

完整示例:

declare
    v_id test.id%TYPE;
    v_type test.type%TYPE;
cursor v_test_cursor is
    select id,type
    from test;
begin
    open v_test_cursor;
    loop
        fetch v_test_cursor
        into v_id,v_type;

        exit when v_test_cursor%NOTFOUND;
        dbms_output.put_line(v_id || v_type);
    end loop;
    close v_test_cursor;
end;

结果:

101
201

2.游标与for循环使用

for循环时,可以不显式的打开和关闭游标。for循环会自动执行这些操作。
例如:

declare 
    cursor v_test_cursor is 
    select id,type  from test;
begin 
    for v_test in v_test_cursor loop 
        dbms_output.put_line(v_test.id || v_test.type); 
    end loop;
end;

结果:

101
201

3.OPEN-FOR语句

可以将游标分配给不同的查询,因此可以灵活的处理游标

declare 
    type t_test_cursor_1 is ref cursor 
    return test%ROWTYPE; --声明的ref cursor(指向游标的指针)类型名为
    t_test_cursor t_test_cursor_1; 
    v_test test%ROWTYPE; --返回test表中各行的一列,v_test用来存储test表的各列。
begin 
    open t_test_cursor for --test表中的所有数据加载到t_test_cursor游标中 
        select * --这里也是要写成*号,如果是字段,就报错!不明白为么????  
        from test;
    loop 
        fetch t_test_cursor into v_test; 
        exit when t_test_cursor%NOTFOUND; --确定何时结束,当不能读出行时,为true,是一个布尔类型 
        dbms_output.put_line(v_test.id || v_test.type);
    end loop;
    close t_test_cursor;
end;

结果:

101
201

4.无约束游标

具有具体的返回类型,为约束游标。
约束游标返回的类型必须与游标运行时返回的类型相匹配。
无约束游标没有返回类型。

declare 
    type t_cursor is ref cursor; 
    v_cursor t_cursor; 
    v_test test%ROWTYPE; 
    v_order order%ROWTYPE;
begin 
    open v_cursor for 
        select * from test;
    loop 
        fetch v_cursor into v_test; 
        exit when v_cursor%NOTFOUND; 
        dbms_output.put_line(v_test.id || v_test.type);
    end loop; 
    open v_cursor for 
        select * from order;
    loop 
        fetch v_cursor into v_order; 
        exit when v_cursor%NOTFOUND; 
        dbms_output.put_line(v_order.id || ' '  ||v_order.status);
    end loop;
    close v_cursor;
end;

结果:

101
201
1   new
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值