1.显示游标
当查询返回结果超过一行时,就需要一个显式游标,此时用户不能使用select into 语句。PL/SQL管理隐式游标,当查询开始时隐式游标打开,查询结束时隐式游标自动关闭。显式游标在PL/SQL块的声明部分声明,在执行部分或异常处理部分打开游标,提取数据并关闭游标。
1.定义游标
cursor cursor_name is select_statement;
.2.打开游标
open cursor_name; //如 open mycursor;
打开游标时,Oracle会执行游标所对应的select 语句,并将select语句的结果暂存到结果集中。
3.提取数据
fetch cursor_name into varible1...
4.关闭游标
close cursor_name
5.显式游标属性
%ISOPEN 判断游标是否打开,如果打开则返回true,否则返回false
%FOUND 检查是否从结果集中提取到数据,如果提取到返回true,否则返回false
%NOT FOUND 该属性与%FOUND相反
ROWCOUNT返回到当前行为止已经提取到的实际行数。
declare
cursor emp_cursor is select ename from scott.emp;
v_name emp.ename%type;
begin
if not emp_cursor %ISOPEN then
open emp_cursor;
end if;
loop
fetch emp_cursor into v_name;
exit when emp_cursor %NOTFOUND;
dbms_output.put_line('姓名:'||v_name);
end loop;
close emp_cursor;
end;
2、使用Fetch bulk collection into 语句提取结果集中的所有数据
declare cursor emp_cursor is select empno,ename,sal from emp;
type emp_table_type is table of emp_cursor%rowtype;
emp_table emp_table_type ;
begin
if not emp_cursor %ISOPEN then
open emp_cursor;
end if;
fetch emp_cursor bulk collect into emp_table;
dbms_output.put_line('rowcount:'||emp_cursor%ROWCOUNT);
close emp_cursor;
end;
3、参数游标
参数游标是指带有参数的游标,在定义参数游标之后,当使用不同参数打开游标时,可以获取不同的结果集
declare cursor mycursor(eno varchar2) is select ename from emp where empno=eno;
v_ename emp.ename%type;
begin
if not mycursor %ISOPEN then
open mycursor('1002');
end if;
loop
fetch mycursor into v_ename;
exit when mycursor %NOTFOUND;
dbms_output.put_line(v_ename);
end loop;
close mycursor;
end;
4.游标的for循环
游标 for 循环简化了对游标的处理,使用游标for循环时,oracle会隐含的打开游标、提取数据并关闭游标,语法如下:
for record_name in cursor_name loop
statement1;
statement2;
end loop
例如:
declare cursor mycursor is select ename from emp;
begin
for v_record in mycursor loop
dbms_output.put_line('第'||mycursor%rowcount||'个员工:'||v_record.ename);
end loop;
end;
在pl/sql语句块中可以使用游标变量,它是指向内存地址的指针,并且可以在打开游标变量时动态指定其对应的select 语句。使用游标包括打开游标、提取数据、关闭游标三个阶段。
declare
type emp_cursor_type is ref cursor; --声明游标类型
emp_cursor emp_cursor_type; --声明游标变量
emp_record emp%rowtype; --定义结构变量
begin
open emp_cursor for select * from emp; --打开有游标
loop
fetch emp_cursor into emp_record; --提取数据
exit when emp_cursor%NOTFOUND;
dbms_output.put_line('employee name:'||emp_record.ename);
end loop;
close emp_cursor; --关闭游标
end;