Oracle学习笔记 part4
异常处理
同其他编程语言,PL/SQL也有自己的异常处理。
declare v_name hls_test_sora.TEST_NAME%type; begin --多数据储存单变量错误 select test_name into v_name from hls_test_sora; exception --利用系统异常判断 when too_many_rows then dbms_output.put_line('输出太多行'); when others then dbms_output.put_line('其他类型的错误'); end;
自定义编号异常,仅在没在系统里的储存编号的异常使用,在此我们仅做简单了解
declare --初始化异常 e_rows_out_exception exception; --给异常配置编号 pragma exception_init(e_rows_out_exception, -1422); v_name hls_test_sora.TEST_NAME%type; begin select test_name into v_name from hls_test_sora; exception --碰到异常触发 when e_rows_out_exception then dbms_output.put_line('太多行'); end;
自定义异常,不论系统自带的异常,仅做自带异常使用
declare --初始化异常 e_too_old_exception exception; v_age hls_test_sora.TEST_AGE%type; begin select test_age into v_age from hls_test_sora where test_id = 5; if v_age > 14 --抛出异常,类似throw then raise e_too_old_exception; end if; exception when e_too_old_exception then dbms_output.put_line('年龄大了'); end;
储存函数
在之前的学习中我们接触过一些函数,在此就快速过一遍函数的结构
以下是一个函数除法的例子
--函数参数中的类型声明均不需要声明大小 CREATE OR REPLACE function my_div_func(param1 number, param2 number) return number is v_sum number; begin v_sum := param1 / param2; return v_sum; exception when ZERO_DIVIDE then dbms_output.put_line('除数不能为0'); return 0; end;
其实这种写法有一种typescript的既视感...
储存过程
过程其实就是一种没有返回值的函数,在此举一个特别好用的例子。
CREATE OR REPLACE procedure --为其声明两个参数,一个是字符串,一个是尾符,并为尾符赋值为chr(13)即为回车符 --拓展:chr函数接受一个数字参数,返回一个对应的ASCII码符号 dbms_print(str varchar2, suffix varchar2 := chr(13)) is begin dbms_output.put(str||suffix); dbms_output.new_line; end;
通过这个过程我们就不需要写dbms_output.put_line这个函数了,直接写dbms_print能少敲不少代码
但是这样写有点问题,就是不能传数字打印,只能是字符串打印。
后来找到了问题的原因,就是dbms_output不识别chr(13)回车符,只能通过dbms_output.new_line方法自己加一个回车符,而且,如果没有回车符,dbms_output会识别出这行没有写完就不会打印。
还有就是,形参可以和实参不一致,会互相转化。
拓展:=>的使用
当函数或者是过程存在多个默认参数的时候,如果你想只改一个参数,可以通过=>来实现
dbms_print(实参=>形参)
--同 dbms_print('myfriends', chr(13))

浙公网安备 33010602011771号