逐行处理查询结果,以编程的方式访问数据
游标的类型:
1、隐式游标:在 PL/SQL 程序中执行DML SQL 语句时自动创建隐式游标,名字固定叫sql。
2、显式游标:显式游标用于处理返回多行的查询。
3、REF 游标:REF 游标用于处理运行时才能确定的动态 SQL 查询的结果
隐式游标:
在PL/SQL中使用DML语句时自动创建隐式游标,隐式游标自动声明、打开和关闭,其名为 SQL,通过检查隐式游标的属性可以获得最近执行的 DML 语句的信息,隐式游标的属性有: %FOUND – SQL 语句影响了一行或多行时为 TRUE,%NOTFOUND – SQL 语句没有影响任何行时为TRUE,%ROWCOUNT – SQL 语句影响的行数,%ISOPEN - 游标是否打开,始终为FALSE
- BEGIN
- UPDATE t_bjqk SET fBL = fBL - 2 WHERE fBJDM=‘1461‘;
- IF SQL%FOUND THEN
- dbms_output.put_line(‘这次更新了‘ || SQL%ROWCOUNT);
- ELSE
- dbms_output.put_line(‘一行也没有更新‘ );
- END IF;
- END;
- 在select中有两个中比较常见的异常: 1. NO_DATA_FOUND 2. TOO_MANY_ROWS
- SQL> declare
- 2 sname1 student.sname%TYPE;
- 3 begin
- 4 select sname into sname1 from student;
- 5 if sql%found then
- 6 dbms_output.put_line(sql%rowcount);
- 7 else
- 8 dbms_output.put_line(‘没有找到数据‘);
- 9 end if;
- 10 exception
- 11 when too_many_rows then
- 12 dbms_output.put_line(‘查找的行记录多于1行‘);
- 13 when no_data_found then
- 14 dbms_output.put_line(‘未找到匹配的行‘);
- 15 end;
- 16 /
- 查找的行记录多于1行
- PL/SQL procedure successfully completed
-
- SQL>
显式游标:
sqlserver与oracle的不同之处在于: 最后sqlserver会deallocate 丢弃游标,而oracle只有前面四步: 声明游标、打开游标、使用游标读取记录、关闭游标。
显式游标的使用:
REF游标也叫动态游标:
qREF 游标和游标变量用于处理运行时动态执行的 SQL 查询 q创建游标变量需要两个步骤: q声明 REF 游标类型 q声明 REF 游标类型的变量 q用于声明 REF 游标类型的语法为:
TYPE <ref_cursor_name> IS REF CURSOR
[RETURN <return_type>];
- declare
- type ref_cursor is ref cursor;
- tab_cursor ref_cursor ;
- sname student.xm %type ;
- sno student.xh %type ;
- tab_name varchar2 (20 );
- begin
- tab_name := ‘&tab_name‘;
- if tab_name = ‘student‘ then
- open tab_cursor for select xh ,xm from student ;
- fetch tab_cursor into sno ,sname ;
- while tab_cursor %found
- loop
- dbms_output.put_line (‘学号:‘ ||sno ||‘姓名:‘ ||sname );
- fetch tab_cursor into sno ,sname ;
- end loop;
- close tab_cursor ;
- else
- dbms_output.put_line (‘没有找到你想要找的表数据信息‘ );
- end if;
- end;
-
-
- SQL > select * from student ;
- XH KC
- 1 语文
- 1 数学
- 1 英语
- 1 历史
- 2 语文
- 2 数学
- 2 英语
- 3 语文
- 3 英语
- 9 rows selected
-
- SQL >
- 完成的任务 :
- 生成student2表 (xh number, kc varchar2 (50 ));
- 对应于每一个学生,求出他的总的选课记录,把每个学生的选课记录插入到student2表中。
- 即,student2中的结果如下:
- XH KC
-
- 1 语文数学英语历史
- 2 语文数学英语
- 3 语文英语
-
- create table student2 (xh number, kc varchar2 (50 ));
-
- declare
- kcs varchar2 (50 );
- kc varchar2 (50 );
- type ref_cursor is ref cursor;
- stu_cursor ref_cursor ;
- type tab_type is table of number;
- tab_xh tab_type ;
- cursor cursor_xh is select distinct( xh) from student;
- begin
- open cursor_xh;
- fetch cursor_xh bulk collect into tab_xh;
- for i in 1 .. tab_xh.count
- loop
- kcs :=‘‘ ;
- open stu_cursor for select kc from student s where s.xh = tab_xh(i );
- fetch stu_cursor into kc ;
- while stu_cursor %found
- loop
- kcs := kc ||kcs ;
- fetch stu_cursor into kc ;
- end loop;
- insert into student2 (xh , kc ) values( i, kcs);
- close stu_cursor ;
- end loop;
- close cursor_xh ;
- end;
oracle游标的使用(二)
原文:http://www.cnblogs.com/sangmu/p/6925608.html