涉及到表的处理请参看原表结构与数据Oracle建表插数据等等
-- 使用select into语句读取tb_Employee的一行,使用异常处理处理no_data_found和two_many_rows的系统预定义异常
set serveroutput on; declare emp tb_Employee%rowtype; begin select * into emp from tb_Employee where ename = 'SCOTT'; dbms_output.put_line('SCOTT ''s sal is : ' || emp.sal); exception when no_data_found then dbms_output.put_line('no data found exception'); end; /
declare emp tb_Employee%rowtype; begin select * into emp from tb_Employee where deptno =20; dbms_output.put_line('The sal is : ' || emp.sal); exception when too_many_rows then dbms_output.put_line('too many rows exception'); end; /
-- 使用嵌套异常端处理,循环读取emp_id_minval 和 emp_id_maxval之间的员工,使得其中存在不存在员工号。输出对应员工的ename,不存在的员工输出“not exists such empolyee”。
declare emp_id tb_Employee.pk_Employee_ID%type; v_ename tb_Employee.ename%type; emp_id_minval tb_Employee.pk_Employee_ID%type; emp_id_maxval tb_Employee.pk_Employee_ID%type; begin emp_id_minval:=&emp_id_minval; emp_id_maxval:=&emp_id_maxval; for emp_id in emp_id_minval..emp_id_maxval loop begin select ename into v_ename from tb_Employee where pk_Employee_ID=emp_id; dbms_output.put_line('ename:'||v_ename); exception when no_data_found then dbms_output.put_line('not exists such empolyee'); end; end loop; end; /
declare insert_excep exception; pragma exception_init(insert_excep, -01400); begin insert into tb_Department (pk_Department_ID, dname) values (50, null); exception when insert_excep then dbms_output.put_line('INSERT OPERATION FAILED'); dbms_output.put_line(SQLERRM); end; /
declare emp tb_Employee % rowtype; error_code number; error_message varchar2(255); begin select * into emp from tb_Employee where ename = 'SCOTT'; dbms_output.put_line('SCOTT ''s salary is : ' || emp.sal); exception when too_many_rows then error_code := SQLCODE; error_message := SQLERRM; dbms_output.put_line(error_code || ' ' || error_message); end; /
declare invalid_department exception; name varchar2(20) := '&name'; deptno number := &deptno; begin update tb_Department set dname = name where pk_Department_ID = deptno; if sql % notfound then raise invalid_department; end if; exception when invalid_department then dbms_output.put_line('No such department'); end; /
declare v_ename tb_Employee.ename%type:='&v_ename'; e_name exception; pragma exception_init(e_name, -20999); begin delete from tb_Employee where ename = v_ename; if sql % notfound then raise_application_error(-20999, 'This is not a valid ename'); end if; exception when e_name then dbms_output.put_line('The ename '||v_ename||' exists, Please choose again'); end; /