CH04_异常答案

作者: 小小蒜头 | 来源:发表于2017-08-28 21:45 被阅读26次
    1. 预定义的异常处理
      根据员工编号或员工姓名查询员工信息,并输出该员工姓名
      如果没有查到该员工,则用 No_data_found 异常处理
      如果查询到多行数据, 则用 Too_many_rows 异常处理
    declare
      v_eno emp.empno%type := &eno;
      v_ename emp.ename%type;
    begin
      select ename into v_ename from emp where empno = v_eno;
      if sql%notfound then 
        raise No_data_found;
        else
        dbms_output.put_line(v_ename);
        end if;
    exception
      when No_data_found then 
      dbms_output.put_line('No_data_found');
      when Too_many_rows then
      dbms_output.put_line('Too_many_rows');
    end;
    
    1. 用户自定义的异常处理
      根据员工编号更新员工工资,如果没有该员工,则抛出异常,
      处理时显示没有些员工,如果是其它异常,则输出该异常的SQLCODE,SQLERRM
    declare
      v_eno emp.empno%type := &eno;
      not_found_empno exception;
      pragma exception_init(not_found_empno,-0001);
    begin
      update emp set sal = sal *1.1 where empno = v_eno;
      if sql%notfound then 
        raise No_data_found;
        end if;
    exception
      when not_found_empno then dbms_output.put_line('not_found_empno');
      when others then dbms_output.put_line('错误代码:'||SQLCODE||',错误号!'||SQLERRM);
    end;
    
    1. 非预定义的异常处理
      向表dept表添加部门信息,声明异常变量,如果部门号存在,则处理该异常
      处理时显示违反了主键约束,输出该异常的SQLCODE,SQLERRM,并显示 raise_application_error
    declare
        e exception;
        pragma exception_init(e,-00001);
      begin
           insert into dept values(10,null,null);
    exception 
           when e then
           dbms_output.put_line('违反了主键约束');
           dbms_output.put_line('错误号'||sqlcode);
           dbms_output.put_line('错误代码'||sqlerrm);
           -- 错误号只能是-20001~-20999
           raise_application_error(-20001,'我自己定义的错误号和代码');
    end; 
    

    相关文章

      网友评论

        本文标题:CH04_异常答案

        本文链接:https://www.haomeiwen.com/subject/gfcndxtx.html