RAISE_APPLICATION_ERROR的两个示例
我们经常通过dbms_output.put_line来输出异常信息,但有时需要把异常信息返回给调用的客户端。此时我们用raise_application_error,允许用户在pl/sql中返回用户自定义的“ORA-”错误代码和错误信息
raise_application_error语法:
raise_application_error(error_number, message[, {TRUE | FALSE}]);
error_number:允许-20000到-20999间的负数
message:允许最长2k的字符串
TRUE:the error is placed on the stack of previous errors.
FALSE:(the default), the error replaces all previous errors.
一、Raising an Application Error With raise_application_error
DECLARE num_tables NUMBER; BEGIN SELECT COUNT(*) INTO num_tables FROM USER_TABLES; IF num_tables < 1000 THEN raise_application_error(-20101, 'Expecting at least 1000 tables'); ELSE NULL; -- Do the rest of the processing (for the non-error case). END IF; END;
二、阻止小于18岁的用户增加到数据库 employee 表中
CREATE OR REPALCE TRIGGER minimun_age_check BEFORE INSERT ON employee FOR EACH ROW BEGIN IF ADD_MONTHS(:new.birth_date,18*12) > SYSDATE THEN
RAISE_APPLICATION_ERROR(-20001,' Employees must at least eighteen years of age. ');
END IF;
END;
下面我们编写一个客户端程序,为了简单,同样用PL/SQL调用
DECLARE no_babies_allowed EXCEPTION; /*将名称与用于触发器中的错误号码关联起来*/ PRAGMA EXCEPTION_INIT(no_babies_allowed, -20001 ); BEGIN INSERT INTO employee ...; EXCEPTION WHEN no_babies_allowed THEN /*||SQLERRM 将传递给内置过程RAISE_APPLICATION_ERROR 的消息返回*/ DBMS_OUTPUT.PUT_LINE(SQLERRM); END ;
引用:
https://www.cnblogs.com/toughhou/p/3778806.html
https://www.cnblogs.com/caizhanshu/articles/1129642.html
浙公网安备 33010602011771号