Orale游标应用.doc
文本预览下载声明
有关异常:如果查询返回空行,PL/SQL抛出no_data_found异常;
如果查询返回多行,PL/SQL抛出too_many_rows异常;
所以在DML之“select into”引发异常时,不能使用sql%notfound属性查看DML是否影响了行
游标过程:
①声明:10天前通知培训
declare
cursor 游标名 is 查询语句;
变量 某表.某列%type;
变量 某表%rowtype;
变量 游标%type;
变量 游标%rowtype;
②打开:培训前一天晚上,打开书包,放三本书
begin
open 游标;
③提取:听课时取出书
loop
fetch 游标 into 变量;
exit when 游标%notfound;
end loop;
④关闭:释放书包
close 游标;
exception
when others then
if 游标%isopen then
close 游标;
end if;
end;
1、用loop 便利游标,注意其格式:
declare
cursor cur is
select empno,ename from emp;
item cur %rowtype; --这里可以改成:item emp%rowtype;
begin
open cur;
loop
fetch cur into item;
exit when cur%notfound ;
end loop;
dbms_output.put_line(item.ename||item.empno);
close cur;
end;
2、
declare
cursor cur is
select ename,job from emp; --这里enamel,job 两列
item emp.ename%type; --定义item是emp表ename列的类型
item2 emp.job%type; --定义item2 是emp表job列类型。 这里声明的变量必须对性查询--出的列对应。
begin
open cur;
loop
fetch cur into item,item2; --捕捉了游标cur 的元素放入,item,item2中。
exit when cur%notfound ; -- 当cur游标都便利完就exit退出。
end loop;
dbms_output.put_line(item||item2);
close cur; --注意关闭游标
end;
用for 、、、in、、、便利游标:
②循环游标,为了简化
隐式打开、自动提取、自动创建“记录索引名 表%rowtype”并用做记录索引、自动关闭
要提取某一列,用“记录索引.某列”
declare
cursor 游标名 is 查询语句;
begin
for 记录索引(不用声明) in 游标
loop
dbms_output.put_line(记录索引.某列);
end loop;
end;
3例子:
declare
cursor cur(i varchar2) is
select *from emp where deptno=i ;
item cur%rowtype;
begin
for admin in cur(20) 注意这里的in。。。 后面跟的是游标 cur 而不是 tiem
--这里可以写成:for admin in cur(部门编号);用通配符,使键盘键入内容。
loop
dbms_output.put_line(admin.ename|| cur%rowcount); --其中cur%rowcount 是有标明%rowcount 显示游标序列
end loop;
end;
4③使用显式游标更新或删除行,为了方便
declare
-- select语句必须只包括一个表
-- 某表不能是“含有distinct、order by的子查询”查询来的结果集(视图)
cursor 游标名 is select 某列 from 某表 for update[ of 某列];
变量 某表.某列%type;
变量 某表%rowtype;
变量 游标%type;
变量 游标%rowtype;
begin
open 游标;
loop
fetch 游标 into 变量;
exit when 游标%notfound;
if 某条件 then
-- update、delete语句只有在打开游标、提取特定行之后才能使用
-- update语句中使用的列必须出现在“select-for update of”语句中
update
显示全部