proc游标和异常

来源:互联网 发布:数据新闻大赛 编辑:程序博客网 时间:2024/05/16 11:17
游标的使用步骤:
       1.  声明游标  
                  cursor   游标名   is   游标中的执行语句
       2.  打开游标
                 open   游标名
       3.  提取数据, 存入指定变量
                fetch    游标名  into  变量名
       4.  关闭游标
               close    游标名
下面来看一定游标的定义方式
          cursor   mycursor   is
                 select   *    from   tablename    where  ;
       或定义有参数的游标
          cursor    mycursor( tid   number)   is
               select   *   from    tablename    where  id=tid;
      如果游标定义时语句还不确定 也可以在open游标是 
       type   mycursor   is   ref   cursor;
       v_cursor    mycursor;
      open    v_cursor    for    'SQL语句'或字符串变量               这样可以动态执行语句   
游标的参数将在open时传入  例子:
        declare

        v_rec temptab%rowtype;
        cursor mycursor(cid number) 
        is 
            select * from temptab
            where id<=cid;
    begin
        open mycursor(2);
        while mycursor%isopen loop              isopen  来判断游标是否打开
            fetch mycursor into v_rec;
            ifmycursor%notfound then               notfound 判断游标中是否有数据
                exit;
            end if;
            dbms_output.put_line(v_rec.id||'   '||v_rec.name);
        end loop;
        close mycursor;                                     关闭游标
    end;

异常:

     异常类型名      

               too_many_rows                 一个变量但却返回多条数据 

         others                        所有其它异常

  绑定异常的错误号

    pragma    exception_init(异常名,绑定的错误号);        绑定后出现此类异常时  错误号为绑定好的

    raise    异常名                                        手动抛出异常

来看一个异常使用的例子

declare
        v_rec temptab%rowtype;
        abc exception;                                    自定义异常
        pragmaexception_init(abc,-0001);                 为异常绑定错误号
    begin
        select * into v_rec from temptabwhere;
        if 2>1 then  
        raise abc;                                         手动抛出异常
        end if;
        insert into temptab valuesv_rec;
        exception
            when too_many_rows then                          出现异常后再excepion标签后进行捕获
            dbms_output.put_line('too_many_rowsexception');
            when abc then
            dbms_output.put_line('abcexception');  
            when others then
            dbms_output.put_line('othersexception');   
    end;--others要放在最后

原创粉丝点击