Chinaunix首页 | 论坛 | 博客
  • 博客访问: 101392048
  • 博文数量: 19283
  • 博客积分: 9968
  • 博客等级: 上将
  • 技术积分: 196062
  • 用 户 组: 普通用户
  • 注册时间: 2007-02-07 14:28
文章分类

全部博文(19283)

文章存档

2011年(1)

2009年(125)

2008年(19094)

2007年(63)

分类: Oracle

2008-04-30 16:14:01

 

execute immediate语句只能用于处理返回单行或没有返回的SQL语句,要处理返回多行的动态SQL就得使用游标.接下来一起讨论游标.
游标是构建在PL/SQL中,用来查询数据,获取记录集合的指针.它可以让开发者一次访问结果集中的一行.
在oracle中提供了两种游标类型,静态游标与REF游标.
1.静态游标
静态游标是在编译时知道其select语句的游标.静态游标又分为两种类型:隐式游标和显式游标.
(1)隐式游标:
用户不能直接命名和控件隐式游标.
隐式游标的属性包括:
%found,%nofound,%rowcount,%isopen
隐式游标实例:
declare
s_id number;
s_rec emp%rowtype;
begin
s_id:=&请输入编号;
select * into s_rec from emp where empno=s_id;
if s_rec.sal<=2000 then
update emp set sal=sal*2 where empno=s_id;
dbms_output.put_line('更新'||sql%rowcount||'行');
else
dbms_output.put_line('工资够高,不用加,呵呵');
end if;
--异常处理
exception
when no_data_found then
dbms_output.put_line('没有此编号');
end;
接收用户输入的编号,查询其编号工资,如果小于2000则更新,否则不更新,最后一个异常处理,如果用户输入的编号不存在,则显示没有此编号.
(2)显式游标:
显式游标是由用户显式声明的游标.根据在游标中定义的查询,查询返回的行集可以包含零行或多行,这些行称为活动集.游标指向活动集的当前行.
显式游标操作的步骤:
声明游标-->打开游标-->从游标中获取记录-->关闭游标.
显式游标可以使用下列语句控制游标.
open:打开游标.
fetch:从游标中提取行.
close:关闭游标.
实例如下:
不带参数的显式游标:
declare
cursor c_cur is select *from emp where deptno=10 for update;
rec emp%rowtype;
begin
open c_cur;
loop
    fetch c_cur into rec;
    exit when c_cur%notfound;
    update emp set sal=sal*2 where current of c_cur;--基于当前游标的更新
end loop;
close c_cur;
end;
带参数的显式游标:
declare
c_num number;
cursor c_cur(dnun number) is select *from emp where deptno=c_num for update;
rec emp%rowtype;
begin
c_num:=&请输入部分编号;
open c_cur(c_num);
    loop
      fetch c_cur into rec;
      exit when c_cur%notfound;
      update emp set sal=sal*2 where current of c_cur;
    end loop;
close c_cur;
end;
循环游标:
循环游标自动打开,提取和关闭游标.实例如下:
declare
cursor c_cur is select *from emp;
begin
for rec in c_cur
loop
    dbms_output.put_line('员工姓名:'||rec.ename);
end loop;
end;
2.REF游标.
隐式游标与显式游标都是静态定义的,当用户使用它们的时候查询语句已经确定.如果用户需要在运行的时候动态决定执行何种查询,可以使用REF游标和游标变量.

OK,来看实例.
declare
type t_ref is ref cursor;
tt t_ref;
in_put char(2);
rec emp%rowtype;
begin
  in_put:='&请输入abc';
  if in_put='a' then
    open tt for select *from emp;
  else
    open tt for select *from t1;
  end if;
  loop
  fetch tt into rec;
  exit when tt%notfound;
  dbms_output.put_line(rec.dname||'薪水'||':'||rec.sal);
  end loop;
end;

解说下,创建游标变量需要两个步骤:声明ref cursor类型和声明ref cursor类型的游标变量,此实例前面三行代码就是创建游标变量.接受用户输入值而决定查询哪个表中的数据,此处需要注意的是,emp与t1表的结构必须是相同的.为什么,dbms_output.put_line(rec.dname||'薪水'||':'||rec.sal);此处要求用户无论输入与哪个表相关的值都得输出这些值,那么就必须要求两表或多表结构相同.
OK,完了.

原文:http://hujing1229.blog.ccidnet.com/blog-htm-do-showone-uid-60604-type-blog-itemid-185875.html

阅读(221) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~