2021年5月11日10:08:15
首先打开输出开关set serveroutput on
使用语句运行@ 'E:\oracledata\hi.txt'
declare
v_n int;
begin
select 12/0 into v_n
from dual;
dbms_output.put_line('测试异常');
exception
when zero_divide then
dbms_output.put_line('除数不能为0');
end;
/
多个值复制一个变量
必须有test这个表,有aa这一列
declare
v_n int;
begin
select aa into v_n
from test;
dbms_output.put_line('测试异常');
exception
when zero_divide then
dbms_output.put_line('除数不能为0');
when too_many_rows then
dbms_output.put_line('多值赋值给一个变量');
end;
/
其他错误
declare
v_n int;
begin
select aa into v_n
from test
where aa = 1000;
dbms_output.put_line('测试异常');
exception
when zero_divide then
dbms_output.put_line('除数不能为0');
when too_many_rows then
dbms_output.put_line('多值赋值给一个变量');
when others then
dbms_output.put_line('其他错误');
end;
/在这里插入代码片
非预定义
非预定没有名
定义一个错误明,错误编码与之对应。
首先删除编号为1的学生,只有编码没有名称,是非预定义的。
declare
del_exc exception;
pragma exception_init(del_exc,-02292);
begin
delete from student
where sno = 1;
dbms_output.put_line('测试异常');
exception
when zero_divide then
dbms_output.put_line('除数不能为0');
when too_many_rows then
dbms_output.put_line('多值赋值给一个变量');
when del_exc then
dbms_output.put_line('不能删除有子记录的主记录');
when others then
dbms_output.put_line('其他错误');
end;
/
查询某个学生的某个成绩,如果小于60,给异常参加补考
首先用sc表,定义一个异常,my_exc ,使用参照行类型,
触发异常if v_grade < 60 then raise my_exc; end if ;exception when my_exc then dbms_output.put_line('成绩不及格参加补考')
declare
my_exc exception;
v_sno sc.sno%type:=&ss;
v_cno sc.cno%type:=&cc;
v_grade sc.grade%type;
begin
select grade into v_grade
from sc
where sno = v_sno and cno = v_cno;
if v_grade < 60 then
raise my_exc;
end if;
exception
when my_exc then dbms_output.put_line('成绩不及格参加补考');
end;
/
declare
exc_small exception;
exc_big exception;
v_n int;
begin
select count(*) into v_n
from student;
if v_n<2 then
raise exc_small;
elsif v_n >3 then
raise exc_big;
end if;
exception
when exc_small then
dbms_output.put_line('学生太少');
when exc_big then
dbms_output.put_line('学生太多');
end;
/