/* 例1:创建的包为demo_pack。 对dept表进行插入、查询和修改操作,并通过demo_pack包中的记录变量 DeptRec 显示所查询到的数据库信息。 该包中包含一个记录类型变量DeptRec、两个函数和一个过程。: */ CREATE OR REPLACE PACKAGE demo_pack IS DeptRec dept%ROWTYPE; FUNCTION add_dept(dept_no NUMBER, dept_name VARCHAR2, location VARCHAR2) RETURN NUMBER; FUNCTION remove_dept(dept_no NUMBER) RETURN NUMBER; PROCEDURE query_dept(dept_no IN NUMBER); END demo_pack;
--包主体部分: CREATE OR REPLACE PACKAGE BODY demo_pack IS FUNCTION add_dept(dept_no NUMBER, dept_name VARCHAR2, location VARCHAR2) RETURN NUMBER IS empno_remaining EXCEPTION; PRAGMA EXCEPTION_INIT(empno_remaining, -1); /* -1 本身是违反唯一约束条件的错误代码,为已预定义DUP_VAL_ON_INDEX */ BEGIN INSERT INTO dept VALUES(dept_no, dept_name, location); IF SQL%FOUND THEN RETURN 1; END IF; EXCEPTION WHEN empno_remaining THEN RETURN 0; WHEN OTHERS THEN RETURN -1; END add_dept; FUNCTION remove_dept(dept_no NUMBER) RETURN NUMBER IS BEGIN DELETE FROM dept WHERE deptno=dept_no; IF SQL%FOUND THEN RETURN 1; ELSE RETURN 0; END IF; EXCEPTION WHEN OTHERS THEN RETURN -1; END remove_dept; PROCEDURE query_dept (dept_no IN NUMBER) IS BEGIN SELECT * INTO DeptRec FROM dept WHERE deptno=dept_no; EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('数据库中没有编码为'||dept_no||'的部门'); WHEN TOO_MANY_ROWS THEN DBMS_OUTPUT.PUT_LINE('程序运行错误!请使用游标'); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(SQLCODE||'----'||SQLERRM); END query_dept; END demo_pack;
DECLARE Var NUMBER; BEGIN Var := demo_pack.add_dept(90,'Administration', 'Beijing'); IF var =-1 THEN DBMS_OUTPUT.PUT_LINE(SQLCODE||'----'||SQLERRM); ELSIF var =0 THEN DBMS_OUTPUT.PUT_LINE('该部门记录已经存在!'); ELSE DBMS_OUTPUT.PUT_LINE('添加记录成功!'); Demo_pack.query_dept(90); DBMS_OUTPUT.PUT_LINE(demo_pack.DeptRec.deptno||'---'|| demo_pack.DeptRec.dname||'---'||demo_pack.DeptRec.loc); var := demo_pack.remove_dept(90); IF var =-1 THEN DBMS_OUTPUT.PUT_LINE(SQLCODE||'----'||SQLERRM); ELSIF var=0 THEN DBMS_OUTPUT.PUT_LINE('该部门记录不存在!'); ELSE DBMS_OUTPUT.PUT_LINE('删除记录成功!'); END IF; END IF; END;
--例子 --包定义 CREATE OR REPLACE PACKAGE demo_pack1 IS DeptRec dept%ROWTYPE; FUNCTION query_dept(dept_no IN NUMBER) RETURN INTEGER; FUNCTION query_dept(dept_no IN VARCHAR2) RETURN INTEGER; END demo_pack1; --包主体 CREATE OR REPLACE PACKAGE BODY demo_pack1 IS FUNCTION query_dept(dept_no IN NUMBER) RETURN INTEGER IS BEGIN IF dept_no =10 THEN SELECT * INTO DeptRec FROM dept WHERE deptno=dept_no; RETURN 1; ELSE RETURN 0; END IF; END query_dept; FUNCTION query_dept(dept_no IN VARCHAR2) RETURN INTEGER IS BEGIN IF dept_no =10 THEN SELECT * INTO DeptRec FROM dept WHERE deptno=dept_no; RETURN 1; ELSE RETURN 0; END IF; END query_dept; END demo_pack1;