游标
pl/sql的游标是指把从数据库中查询出来的数据,以临时表的形式存放在内存中,游标可以对存储在内存中的数据进行操作,返回一条线或一组记录,或者一条也不返回.
pl/sql中的记录和表类型虽然可以存储数据,但是对存在内存中的数据进行操作比较麻烦,游标就是解决内存查询到数据进行处理改变.
1.声明游标
cursor cursor_name is select…
2.打开游标
open cursor_name
3.提取游标
fetch cursor_name into variable1,variable2…
4.关闭游标
close cursor_name
cursor cursor_name is select…
cursor : 游标关键字
cursor_name : 游标名称
select :建立游标所使用的的查询语言
游标属性
1.%isopen 属性主要用于判断游标是否打开,在使用游标的时候如果不能确定是否已经打开,可以判断使用(未打开的游标不可以提取)
2.%found 属性主要用于判断游标是否找到记录,如果找到记录用fetch语句提取游标数据
3.%notfound 如果提取到数据返回false,否则返回true和%found正好相反
4.%rowcount 该属性用于返回到当前提取的实际行数
declare
cursor c_emp is select * from emp;
v_emp emp%rowtype;
begin
open c_emp;
fetch c_emp into v_emp;
while c_emp%found loop
dbms_output.put_line(c_emp%rowcount||' '||v_emp.ename|| ' '||v_emp.sal);
fetch c_emp into v_emp;
end loop;
if c_emp%isopen then
close c_emp;
end if;
end;
参数化游标
定义游标后,使用后在传参
cursor cursor_name(paramter) is select…
-- Created on 2019-09-04 by LINNE
declare
cursor emp_cursor(dno number) is select ename from emp where deptno = dno;
v_ename emp.ename%type;
begin
-- Test statements here
open emp_cursor(20);
loop
fetch emp_cursor into v_ename;
dbms_output.put_line(v_ename);
exit when emp_cursor%notfound;
end loop;
close emp_cursor;
dbms_output.put_line('---------------------------------');
open emp_cursor(10);
loop
fetch emp_cursor into v_ename;
dbms_output.put_line(v_ename);
exit when emp_cursor%notfound;
end loop;
close emp_cursor;
end;
游标for循环
游标for循环是在pl/sql块中使用游标最简单的方式,简化了游标的处理,Oracle会隐含的打开游标,提取游标,关闭游标.
for record in cursor_name loop
.....
end loop;
declare
cursor c_dept(dno number) is select * from dept where deptno = dno;
begin
for v_dept in c_dept(20) loop
dbms_output.put_line('第'||c_dept%rowcount||'个员工'||v_dept.dname);
end loop;
end;
隐式游标
在执行一个SQL语句的时候,Oracle服务器将自动创建一个隐式游标,隐式游标的固定名称SQL,隐式游标不需要声明和打开,使用完也不需要关闭.
隐式游标只能处理一行数据,所以into只能给一组变量赋值!
异常
pl/sql程序运行期间经常会发生各种异常,一旦异常,如果不进行处理程序就会被终止,Oracle系统将异常分为预定义异常和自定义异常.
EXCEPTION
when exception1 then
.....
when exception2 then
.....
when others then
.....
如果异常都不匹配,将执行orthers中的代码
timeout_on_resource : 等待资源发生超时
invalid_cursor : 使用了一个无效的游标
no_logged_on :未连接Oracle
login_denied : 无效的用户名和密码
no_data_found : 没有找到数据(into)
zero_divide : 视图被零除
value_error : 转换或截断错误