2012年5月17日星期四

oracle sqlerrm . sqlcode

1.oracle sqlcode函数

sqlcode函数用来返回pl/sql执行内部异常代码。
语法:sqlcode
oracle sqlerrm函数
sqlerrm函数返回指定错误代码的错误信息。
语法:SQLERRM [(error_number)]
2.sqlerrm如何使用?
sqlcode和sqlerrm是不能直接在sql语句中使用,必须先将其赋给变量后,才能在sql语句中使用,如下:

dw@dw>
declare
  v_sqlcode number;
  v_sqlcode1 number;
  v_sqlerrm varchar2(510);
 begin
  v_sqlcode :=sqlcode;
  select v_sqlcode into v_sqlcode1 from dual;
 end;
  /

PL/SQL 过程已成功完成。

sqlerrm用得最多的是在pl/sql编程中来捕获异常的详细信息,特别是在when others 中使用非有用。
如下:
view plaincopy to clipboardprint?

set serveroutput on
declare
   v_count pls_integer;
begin
   begin
   select 2 into v_count from dual where 1>2;
   exception
   when others then
   dbms_output.put_line(sqlerrm);
end;
begin
select level into v_count
from dual
connect by level < 3;
end;
end;
/

dw@dw>set serveroutput on
dw@dw>declare
  v_count pls_integer;
 begin
  begin
  select 2 into v_count
  from dual where 1>2;
  exception
  when others then
  dbms_output.put_line(sqlerrm);
  end;
begin
  select level into v_count from dual
  connect by level < 3;
  end;
 end;
  /
ORA-01403: 未找到任何数据
declare
*
第 1 行出现错误:
ORA-01422: 实际返回的行数超出请求的行数
ORA-06512: 在 line 12

3.sqlerrm的最大长度是多少?
其实这个问题很好解答,自定义一个异常,然后用sqlerrm去捕获即可。
view plaincopy to clipboardprint?

set serveroutput on
begin
  raise_application_error(-20001,
  'sqlerrm的最大长度是多少' || lpad('我', 10000, '我'));
  exception
  when others then
  dbms_output.put_line(lengthb(sqlerrm));
end;
/
dw@dw>
begin
  raise_application_error(-20001,
  'sqlerrm的最大长度是多少' || lpad('我', 10000, '我'));
  exception
  when others then
  dbms_output.put_line(lengthb(sqlerrm));
 end;
  /

PL/SQL 过程已成功完成。
dw@dw>
从输出结果来看,oracle sqlerrm的最在长度为510个字节。
4.oracle ora-错误信息手册

从oracle的参考文档中,可以发现自定义异常从-20000开始,也就是说,
-20000前的数据都是oracle内部使用的,
可以通过下面这段匿名块查出oracle所有ora-错误信息。
view plaincopy to clipboardprint?

set serveroutput on
exec dbms_output.enable(10000000);
begin
   for i in 0..20000 loop
   dbms_output.put_line(sqlerrm(-i));
   end loop;
end;
/

没有评论:

发表评论