posts - 710,  comments - 81,  views - 260万
< 2025年3月 >
23 24 25 26 27 28 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 29
30 31 1 2 3 4 5

目的:
        和ref cursor配合使用, 可以将游标变量分配给不同的SQL (而不是在declare中把游标给定死), 增加处理游标的灵活性
语法:

1
2
3
4
5
6
7
8
declare
    type type_cursor  is ref cursor [return 记录类型];  --使用 ref cursor 才能把游标分配给不同的SQL,return不能用在动态SQL中
    v_cursor type_cursor ;
begin
    OPEN v_cursor FOR select first_name, last_name from student;
 
    OPEN v_cursor FOR ' select first_name,last_name  from student where zip = :1 '
    USING 绑定变量1;

  

 

open 静态SQL cursor cursor c1 is <静态SQL文本>
open c1; fetch ... into ... ; close c1;
open for     静态SQL     ref cursor type t_1 is ref cursor;
c2  t_1 ;
open c2 for <静态SQL语句>;
open for using 动态SQL type t_1 is ref cursor;
c2  t_1 ;
open c2 for <动态SQL语句> using ... ;

例子1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
declare
  type student_cur_type is ref CURSOR RETURN test_stu%ROWTYPE;  --声明ref cursor类型, return类型固定
    v_first_name test_stu.first_name%TYPE;
    v_last_name test_stu.last_name%TYPE;
  cur_stud student_cur_type;
begin
  open cur_stud for select first_name,last_name from student ;  --带return的ref cursor只能用在静态sql中
 loop
    fetch cur_stud into v_first_name, v_last_name;
    exit when cur_stud%NOTFOUND;
    dbms_output.put_line(v_first_name || ' ' || v_last_name);
  end loop;
  close cur_stud;
end;

  

例子2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
declare
  v_zip        varchar2(5) := '&sv_zip';
  v_first_name varchar2(25);
  v_last_name  varchar2(25);
  
  type student_cur_type is ref cursor--声明ref cursor类型
  student_cur student_cur_type;  --student_cur是游标变量 / student_cur_type 是引用游标类型
begin
  --2打开游标变量,让它指向一个动态select查询的结果集 ; 就是使用open for语句代替一般的open语句代开游标
  open student_cur for 'select first_name,last_name ' from student where zip = :1'
    using v_zip;
  loop
    fetch student_cur into v_first_name, v_last_name;
    exit when student_cur%NOTFOUND;
    dbms_output.put_line(v_first_name || ' ' || v_last_name);
  end loop;
  close student_cur;
end;

  

转载自:https://blog.csdn.net/crzzyracing/article/details/75336196  

posted on   itprobie-菜鸟程序员  阅读(6929)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2016-06-13 如何MSHTML命名空间解析HTML文件(MSHTML::IHTMLDocument2Ptr 提示错误)
2013-06-13 正则表达式语法
点击右上角即可分享
微信分享提示