EXCEPTION
WHEN first_exception THEN <code to handle first exception >
WHEN second_exception THEN <code to handle second exception >
WHEN OTHERS THEN <code to handle others exception >
--例1:更新指定员工工资,如工资小于1500,则加100;
DECLARE
v_empno employees.employee_id%TYPE := &empno;
v_sal employees.salary%TYPE;
BEGIN
SELECT salary INTO v_sal FROM employees WHERE employee_id = v_empno;
IF v_sal<=1500 THEN
UPDATE employees SET salary = salary + 100 WHERE employee_id=v_empno;
DBMS_OUTPUT.PUT_LINE(‘编码为‘||v_empno||‘员工工资已更新!‘);
DBMS_OUTPUT.PUT_LINE(‘编码为‘||v_empno||‘员工工资已经超过规定值!‘);
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(‘数据库中没有编码为‘||v_empno||‘的员工‘);
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE(‘程序运行错误!请使用游标‘);
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLCODE||‘—‘||SQLERRM);
--例2:删除指定部门的记录信息,以确保该部门没有员工。
INSERT INTO departments VALUES(50, ‘FINANCE‘, ‘CHICAGO‘);
DECLARE
v_deptno departments.department_id%TYPE := &deptno;
deptno_remaining EXCEPTION;--定义一个异常变量
PRAGMA EXCEPTION_INIT(deptno_remaining, –2292); /* -2292 是违反一致性约束的错误代码 */
BEGIN
DELETE FROM departments WHERE department_id = v_deptno;
EXCEPTION
WHEN deptno_remaining THEN
DBMS_OUTPUT.PUT_LINE(‘违反数据完整性约束!‘);
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLCODE||‘—‘||SQLERRM);
--例3:更新指定员工工资,增加100;
DECLARE
v_empno employees.employee_id%TYPE :=&empno;
no_result EXCEPTION;-定义异常
BEGIN
UPDATE employees SET salary = salary+100 WHERE employee_id = v_empno;
IF SQL%NOTFOUND THEN
RAISE no_result;//触发异常
END IF;
EXCEPTION
WHEN no_result THEN //捕捉异常
DBMS_OUTPUT.PUT_LINE(‘你的数据更新语句失败了!‘);
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLCODE||‘—‘||SQLERRM);
CREATE OR REPLACE FUNCTION get_salary(p_deptno NUMBER) #函数检索指定部门的工资总和
RETURN NUMBER
v_sal NUMBER; #函数get_salary返回v_sal值
BEGIN
IF p_deptno IS NULL THEN
RAISE_APPLICATION_ERROR(–20991, '部门代码为空'); #用户定义的异常处理
ELSIF p_deptno<0 THEN
RAISE_APPLICATION_ERROR(–20992, '无效的部门代码');
SELECT SUM(employees.salary) INTO v_sal FROM employees
WHERE employees.department_id=p_deptno;
RETURN v_sal;
END IF;
DECLARE
V_salary NUMBER(7,2);
V_sqlcode NUMBER;
V_sqlerr VARCHAR2(512);
Null_deptno EXCEPTION; #定义异常情况
Invalid_deptno EXCEPTION; #定义异常情况
PRAGMA EXCEPTION_INIT(null_deptno,–20991); #非预定义的异常,将它与oracle错误联系起来
PRAGMA EXCEPTION_INIT(invalid_deptno, –20992); #非预定义的异常,将它与oracle错误联系起来
BEGIN
BEGIN
V_salary :=get_salary(–10);
EXCEPTION
WHEN invalid_deptno THEN
V_sqlcode :=SQLCODE;
V_sqlerr :=SQLERRM;
INSERT INTO errlog(errcode, errtext) VALUES(v_sqlcode, v_sqlerr); #将错误SQLCODE及SQLERRM存入到表errlog中
COMMIT;
END ;
CREATE OR REPLACE TRIGGER tr_insert_emp
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
IF :new.first_name IS NULL OR :new.last_name is null THEN
RAISE_APPLICATION_ERROR(–20000,‘Employee must have a name.‘);
END IF;