oracle游标

/*
游标:用于临时存储从数据库提取的数据块。

一次提取一行数据,使用隐式游标
一次提取多行数据,使用显式游标

游标一旦打开,数据就从数据库中传送到游标变量中

隐式游标:
DML操作和select语句会使用隐式游标

通过隐式游标的属性来了解操作的状态和结果,进而控制程序的流程。
隐式游标可以使用名字sql来访问,通过sql游标名总是只能访问前一个dml操作或单行select操作的游标属性

游标属性有4种:

隐式游标的属性 返回值类型 意义
sql%rOWCOUNT 整型 代表dml语句成功执行的数据行数
sql%FOUND 布尔型 值为TRUE代表插入、删除、更新或单行查询操作成功
sql%NOTFOUND 布尔型 与sql%FOUND属性返回值相反
sql%ISOPEN 布尔型 dml执行过程中为真,结束为假

显式游标:
游标使用分4个步骤
1.声明游标
cursor 游标名 [(参数1,数据类型,参数2,数据类型...)]
is select 语句;
参数可选,所定义的参数出现在select语句的where子句中,如果定义了参数,必须在打开游标时传递响应的参数。
SELECT语句中可以使用在定义游标之前定义的变量,但不能使用into子句。

2.打开游标
open 游标名[(实参1,实参2...)]
打开游标时,select语句的查询结果就传送到了游标工作区

3.提取数据
fetch 游标名 into 变量1[,变量2...];

fetch 游标名 into 记录变量;

fetch语句一次返回指针所指的一行数据,要返回多行需重复执行,可使用循环语句来实现。控制循环可以通过判断游标的属性来进行。

第一种格式:变量是用来从游标中接收数据的变量,需事先定义,变量个数和类型与select查询的字段个数和类型一致
第二种格式:一次将一行的数据提取到记录变量中,需使用%rOWTYPE事先定义记录变量

记录变量定义格式:变量名 表名|游标名%rOWTYPE;

4.关闭游标
close 游标名;

显示游标属性
游标的属性 返回值类型 意义
%rOWCOUNT 整型 获得fetch语句返回的数据行数
%FOUND 布尔型 最近的fetch语句返回一行数据则为真,否则为假
%NOTFOUND 布尔型 与%FOUND属性返回值相反
%ISOPEN 布尔型 游标已经打开时为真,否则为假

可按照以下形式取得游标的属性

游标名%属性

动态游标:
变量声明部分定义的游标是静态的,不能在程序运行过程中修改
虽然可以通过参数传递来取得不同的数据,但还是有很大的局限性。

通过采用动态游标,可以在程序运行阶段随时生成一个查询语句作为游标。
要使用动态游标需要先定义一个游标类型,然后声明一个游标变量,
游标对应的查询语句可以在程序的执行过程中动态地说明。

定义游标类型语句:
type 游标类型名 REF cursor;

声明游标变量语句:
游标变量名 游标类型名;

打开动态游标:
open 游标变量名 for 查询语句字符串;

异常处理:
位于程序的可执行部分之后,由when语句引导的多个分支构成
exception
when 错误1 then
语句序列1;
when 错误2 then
语句序列2;
when others
语句序列n;
end;

错误是在标准包中由系统预定义的标准错误,或是由用户在程序的说明部分自定义错误
语句序列是不同分支的错误处理分别。
如要在该分支中进一步判断错误种类,可以通过使用预定义函数sqlCODE( )和sqlERRM( )来获得系统错误号和错误信息。

如果在程序的子块中发生了错误,但子块没有错误处理部分,则错误会传递到主程序中。

预定义错误
Oracle的系统错误很多,但只有一部分常见错误在标准包中予以定义。
定义的错误可以在EXCEPTION部分通过标准的错误名来进行判断,并进行异常处理。
常见的系统预定义异常如下所示。

错 误 名 称 错误代码 错 误 含 义
CURSOR_ALREADY_OPEN ORA_06511 试图打开已经打开的游标
INVALID_CURSOR ORA_01001 试图使用没有打开的游标
DUP_VAL_ON_INDEX ORA_00001 保存重复值到惟一索引约束的列中
ZERO_DIVIDE ORA_01476 发生除数为零的除法错误
INVALID_NUMBER ORA_01722 试图对无效字符进行数值转换
ROWTYPE_MISMATCH ORA_06504 主变量和游标的类型不兼容
VALUE_ERROR ORA_06502 转换、截断或算术运算发生错误
TOO_MANY_ROWS ORA_01422 SELECT…INTO…语句返回多于一行的数据
NO_DATA_FOUND ORA_01403 SELECT…INTO…语句没有数据返回
TIMEOUT_ON_RESOURCE ORA_00051 等待资源时发生超时错误
TRANSACTION_BACKED_OUT ORA_00060 由于死锁,提交失败
STORAGE_ERROR ORA_06500 发生内存错误
PROGRAM_ERROR ORA_06501 发生PL/sql内部错误
NOT_LOGGED_ON ORA_01012 试图操作未连接的数据库
LOGIN_DENIED ORA_01017 在连接时提供了无效用户名或口令

自定义异常:
可以在声明部分定义新的异常类型,定义的语法是:
错误名 EXCEPTION;
用户定义的错误不能由系统触发,必须由程序显式触发,触发的语法是:
raise 错误名;

raise也可以用来引发模拟系统错误,比如:raise ZERO_diveDE引发模拟的除零错误.
使用RAISE_APPLICATION_ERROR函数也可以引发异常。该函数要传递两个参数,
一个用户自定义错误编号,第二个参数是用户自定义错误信息。使用该函数引发的异常的编号应该在20000和20999之间选择。


*/

1.使用隐式游标的属性,判断对雇员的工资修改是否成功
    begin
      update luffy.student_test a set a.tot_cred = a.tot_cred + 1 where a.id = 40116;
      if sql%FOUND then
        DBMS_OUTPUT.put_line('修改学生学分成功'); 
      commit;
      else
        DBMS_OUTPUT.put_line('修改学生学分失败');
       end if;
     end;
<pre name="code" class="sql">--2.显示游标
 
declare
v_name varchar2(20);
v_cred number(3);
cursor stu_cursor is
select a.name,a.tot_cred from luffy.student_test a where a.id = 40116;

begin
open stu_cursor;
fetch stu_cursor
into v_name,v_cred;
dbms_output.put_line(v_name || ',' || v_cred);
close stu_cursor;
end;    
--3.显示游标 使用记录变量

declare
    cursor stu_cursor is select a.name,a.tot_cred,a.dept_name from luffy.student_test a where a.id = 40116;
    stu_record stu_cursor%rOWTYPE; --记录变量
    
begin
  open stu_cursor;
  fetch stu_cursor into stu_record;
       dbms_output.put_line(stu_record.name || ',' || stu_record.tot_cred || ',' || stu_record.dept_name);
  close stu_cursor;
end;



--4显示游标 显示学分最高的3位学生的姓名和学分
--该程序在游标定义中使用了ORDER BY子句进行排序,并使用循环语句来提取多行数据。 
declare
v_name varchar2(20);
v_cred number(3);
cursor stu_cursor is
select a.name,a.tot_cred from luffy.student_test a order by a.tot_cred desc;
begin
open stu_cursor;
for I in 1..10 loop
fetch stu_cursor
into v_name,' || v_cred);
end loop;
close stu_cursor;
end;



--5.使用特殊的for循环显示 前100条学生信息
--可以看到该循环形式非常简单,隐含了记录变量的定义、游标的打开、提取关闭过程。
--stu_record为隐含定义的记录变量,循环的执行次数与游标取得的数据的行数相一致。 
declare
 cursor stu_cursor is 
      select a.name,a.dept_name,a.tot_cred from luffy.student_test a where rownum <= 100;
 begin
for stu_record in stu_cursor loop
dbms_output.put_line(stu_record.name || ',' || stu_record.dept_name || ',' ||
stu_record.tot_cred);
end loop;
 end;  

--6.使用游标的属性练习
 declare
v_name varchar2(20);
v_cred number(3);
cursor stu_cursor is
select a.name,a.tot_cred from luffy.student_test a where rownum <= 4;

begin
open stu_cursor;
if stu_cursor%ISOPEN then
loop
fetch stu_cursor
into v_name,v_cred;
exit when stu_cursor%NOTFOUND;
dbms_output.put_line(v_name || ',' || v_cred);
end loop;
    dbms_output.put_line('查找数量:' || stu_cursor%rOWCOUNT);
else
dbms_output.put_line('没有打开游标');
end if;
close stu_cursor;
end;    

--7.动态select语句和动态游标的用法
 --对于查询结果为一行的SELECT语句,可以用动态生成查询语句字符串的方法
 --execute immediate 查询语句字符串 into 变量1[,变量2...]; 
 declare 
 v_name varchar2(100);
 v_cred number(3);
 str varchar2(150);
 begin
   str :='select name,tot_cred from luffy.student_test a where a.id = 40116';
   execute immediate str into v_name,v_cred;
   dbms_output.put_line(v_name || ',' || v_cred);
 end;

--8.按名字中包含的字母顺序分组显示学生信息。
--使用了二重循环,在外循环体中,动态生成游标的SELECT语句,然后打开。
--通过语句letter:=chr(ascii(letter)+1)可获得字母表中的下一个字母。 
declare
     type cur_type is ref cursor;
     cur cur_type;
     rec luffy.student_test%rowtype;--
     str varchar2(100);--动态sql
     letter char := '';
  begin
    loop
      str := 'select name from luffy.student_test a where a.name like ''%' || letter || '%''';
      open cur for str;
      dbms_output.put_line('包含字母'||letter||'的名字: ');
       loop
         fetch cur into rec.name;
         exit when cur%notfound;
         dbms_output.put_line(rec.name);
        end loop;
        exit when letter='Z';
        letter := chr(ascii(letter)+1);
    end loop;
  end;

--9.异常处理
--“NO_DATA_FOUND”是系统预定义的错误类型
 declare
v_name varchar2(20);
 begin
select name into v_name from luffy.student_test a where a.id = 1234;
dbms_output.put_line('该学生名字为:' || v_name);
 exception
when no_data_found then
dbms_output.put_line('id错误,没有找到对应的学生。');
when others then
dbms_output.put_line('发生其他错误!');
 end;  

--10.由程序代码显示系统错误
DECLARE
v_temp NUMBER(5) := 1;
BEGIN
v_temp := v_temp / 0;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('发生系统错误!');
DBMS_OUTPUT.PUT_LINE('错误代码:' || sqlCODE());
DBMS_OUTPUT.PUT_LINE('错误信息:' || sqlERRM());
END;     

--11.定义新的错误类型
--说明:NULL_INSERT_ERROR是自定义异常,同系统错误1400相关联。 
DECLARE
V_ENAME VARCHAR2(10);
NULL_INSERT_ERROR EXCEPTION;
PRAGMA EXCEPTION_INIT(NULL_INSERT_ERROR,-1400);
BEGIN
INSERT INTO luffy.student_test (name) VALUES (NULL);
EXCEPTION
WHEN NULL_INSERT_ERROR THEN
DBMS_OUTPUT.PUT_LINE('无法插入NULL值!');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('发生其他系统错误!');
END;    

--12.自定义异常
--插入新学生信息,限定插入id的编号在80000~90000之间
declare
new_id number(5);
new_excp1 exception;
new_excp2 exception;

begin
new_id := 70000;
insert into luffy.student_test (id,name,dept_name,tot_cred)
values (new_id,'luffysan','haizei',5);

if new_id < 80000 then
raise new_excp1;
end if;
if new_id > 90000 then
raise new_excp2;
end if;
commit;
exception
when new_excp1 then
rollback;
dbms_output.put_line('学生id号小于80000!');
when new_excp2 then
rollback;
dbms_output.put_line('学生id号大于90000!');
end;  

--13. 使用RAISE_APPLICATION_ERROR函数引发系统异常。
declare 
   new_id := 22222;
    insert into luffy.student_test (id,tot_cred)
  values (new_id,5);
    if new_id < 80000 then
      rollback;
      raise_application_error();
    end if;

--14.通过指定编号将学生从一个表负责到另一个
--说明:stu_rec变量是根据student_test表定义的记录变量,SELECT...INTO...语句将整个记录传给该变量。
--INSERT语句将整个记录变量插入student_test2表,如果插入成功(sql%FOUND为真),则提交事务,否则回滚撤销事务
 declare 
 v_id number(5) := 33546;
 stu_rec student_test%rowtype;
 begin
   select * into stu_rec from luffy.student_test a where id = v_id;
   insert into luffy.student_test2 values stu_rec;
   if sql%found then
     commit;
     dbms_output.put_line('复制成功!');
     else
       rollback;
     dbms_output.put_line('复制失败');
    end if;
  end;

--15.输出学生学分,学分用不同高度的*表示
 --第一个rpad函数产生对齐效果,第二个rpad函数根据学分产生不同数目的*。
 --该程序采用了隐式的简略游标循环形式。 
 begin
for re in (select name,tot_cred
from luffy.student_test a
where rownum <= 1000) loop
dbms_output.put_line(rpad(re.name,12,' ') ||
rpad('*',re.tot_cred/2,'*'));
end loop;
 end;        

--16. 格式化输出学院信息
declare
 v_count number := 0;
 cursor dept_cursor is select * from luffy.department a;
 begin
    dbms_output.put_line('学院信息');   
    dbms_output.put_line('-----------------------------------');  
    for dept_record in dept_cursor loop
      dbms_output.put_line('学院名称:' || dept_record.DEPT_NAME);
      dbms_output.put_line('学院建筑楼:' || dept_record.BUILDING);
      dbms_output.put_line('学院经费:' || dept_record.BUDGET);
    dbms_output.put_line('-----------------------------------'); 
     v_count := v_count + 1;
     end loop;
     dbms_output.put_line('共有' || to_char(v_count) || '个学院!');
  end;

--17.输出学院名称、学院总人数、总学分
declare
 v_count number(5);
 v_sum   number(5);
 v_dname varchar2(50);
 
 cursor list_cursor is
      select a.dept_name,count(*),sum(a.tot_cred) from luffy.student_test a group by a.dept_name;
 begin
   open list_cursor;
   dbms_output.put_line('--------------------学院统计-----------------');
   dbms_output.put_line('学院名称    总人数      总学分  ');    
   fetch list_cursor into  v_dname,v_count,v_sum;
   while list_cursor%found loop
     select a.dept_name into v_dname from luffy.department a
     where a.dept_name = v_dname;
     
     dbms_output.put_line(rpad(v_dname,15) || rpad(to_char(v_count),8) 
                                           || rpad(to_char(v_sum),10));
                          
     fetch list_cursor into v_dname,v_sum;
     end loop;
     dbms_output.put_line('---------------------------------------------');
  close list_cursor;
  end; 


--18.修改学分

--为学生增加学分
declare
  v_name varchar2(20);
  v_cred number(3);  
  v_addcred number(2) := 10;--增加的学分
  v_num number(4) := 0; --增加学分的人数
  cursor stu_cursor is
  select a.name,a.tot_cred from luffy.student_test a order by a.tot_cred asc;
  begin
    open stu_cursor;
    dbms_output.put_line('------------------------');
    loop
      fetch stu_cursor into v_name,v_cred ;
      exit when stu_cursor%notfound;
      if v_cred < 50 then
        v_cred := v_cred + v_addcred;
        v_num := v_num + 1;
       dbms_output.put_line(v_name || to_char(v_cred,'9999') || to_char(v_cred + v_addcred,'9999') );
       update luffy.student_test 
       set tot_cred = tot_cred + v_addcred
       where name = v_name;
      else
       dbms_output.put_line(v_name || to_char(v_cred,'9999') ||  to_char(v_cred,'9999'));
      end if;
     end loop;
     dbms_output.put_line('----------------------------');
     dbms_output.put_line('增加学分的人数:' || v_num);
     close stu_cursor;
    -- commit;
end;

相关文章

Java Oracle 结果集是Java语言中处理数据库查询结果的一种方...
Java AES和Oracle AES是现代加密技术中最常使用的两种AES加密...
Java是一种广泛应用的编程语言,具备可靠性、安全性、跨平台...
随着移动互联网的发展,抽奖活动成为了营销活动中不可或缺的...
Java和Oracle都是在计算机领域应用非常广泛的技术,他们经常...
Java 是一门非常流行的编程语言,它可以运行于各种操作系统上...