您的位置:首页 > 数据库 > Oracle

SQL-Oracle游标

2015-08-24 16:53 337 查看
游标提供了一种从集合性质的结果集中提供出单条记录的手段,初始时指向首记录。

游标的种类

静态游标、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语句的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: