-- 十三、异常
/* 运行时发生的错误
exception
when 异常种类 then
处理语句;
when 异常种类 then
处理语句;
when others then
处理语句;
insert/select用异常
update/delete用隐式游标
*/
-- 1.预定义异常
-- 1)dup_val_on_index:试图破坏唯一性
begin
insert into dept values(10,'wdss','sfddg');
exception
when dup_val_on_index then
dbms_output.put_line('数据已经存在');
when others then
dbms_output.put_line('其他异常');
end;
-- 2)no_data_found:没有找到数据
-- 3)too_many_rows:找到多行数据
-- 找某个指定部门编号的员工姓名和工资
select * from emp
declare
dno number;
xm varchar2(20);
salary number;
begin
dno:=&输入编号;
select ename,sal into xm,salary from emp
where deptno=dno;
dbms_output.put_line('姓名'||xm);
dbms_output.put_line('工资'||salary);
exception
when no_data_found then
dbms_output.put_line('没有找到数据');
when too_many_rows then
dbms_output.put_line('找到多行数据');
end;
-- 更新指定编号的员工工资
declare
eno number;
money number;
begin
eno:=&输入一个编号;
money:=&输入要更新的工资值;
update emp set sal=sal+money
where empno=eno;
if sql%notfound then
dbms_output.put_line('没有更新数据');
else
dbms_output.put_line('更新成功');
end if;
end;
-- 删除指定编号的员工工资
declare
eno number;
begin
eno:=&输入一个编号;
delete from emp
where empno=eno;
if sql%notfound then
dbms_output.put_line('没有删除的数据');
else
dbms_output.put_line('删除成功');
end if;
end;
-- zero_divide 除零异常
-- 2.自定义异常
declare
num number;
myException exception;
begin
num:=&输入一个人数;
if num<=0 then
raise myException;
end if;
dbms_output.put_line(num);
exception
when myException then
dbms_output.put_line('不能为负数');
when too_many_rows then
dbms_output.put_line('找到多行数据');
when others then
dbms_output.put_line('其他异常');
end;
-- 十四、同义词
-- 现有对象的别名,提高访问的安全性。
/* 1)公有同义词
create public synonym 同义词名 for 用户.表名 */
在系统用户下创建:
create public synonym myemp for scott.emp;
-- 访问:
-- 可以在系统用户下访问,还可以在表本身所在的用户下访问同义词
-- 还可以在授权的用户下访问
/* 2)私有同义词
create synonym 同义词名 for 用户.表名 */
-- 在系统用户下创建:
create synonym mydept for scott.dept;
-- 只能在系统用户下访问