ORACLE相关语法--子程序和程序包(package,function,procedure)(二)
re pro_print_sal(id number);
function fun_re_date(id number) return date;
end;
创建包主体的语法:
CREATE [OR REPLACE] PACKAGE BODY package_name IS|AS [Public type and item declarations] [Subprogram bodies] [BEGIN Initialization_statements] END [package_name];
其中:package_name是包的名称。
Public type and item declarations是声明类型、常量、变量、异常和游标等。
Subprogram bodies是定义公共和私有PL/SQL子程序。
示例7:演示创建程序包主体
create or replace package body pack_op is
procedure pro_print_ename(id number) is
name emp.ename%type;
begin
select ename into name from emp where empno=id;
dbms_output.put_line('职员姓名:'||name);
end pro_print_ename;
procedure pro_print_sal(id number) is
salary emp.sal%type;
begin
select sal into salary from emp where empno=id;
dbms_output.put_line('职员工资:'||salary);
end pro_print_sal;
function fun_re_date(id number) return date is
bedate emp.hiredate%type;
begin
select hiredate into bedate from emp where empno=id;
return bedate;
end fun_re_date;
end pack_op;
示例8:调用程序包中创建的过程和函数
exec pack_op.pro_print_ename(7900);
exec pack_op.pro_print_sal(7900);
select pack_op.fun_re_date(7900) from dual;
示例9:演示程序包中的游标
创建包规范
create or replace package pack_emp is cursor cur_emp return emp%rowtype; procedure pro_cur; end pack_emp;
创建包主体
create or replace package body pack_emp is
cursor cur_emp return emp%rowtype is
select * from emp;
procedure pro_cur is
rec_emp emp%rowtype;
begin
open cur_emp;
loop
fetch cur_emp into rec_emp;
exit when cur_emp%notfound;
if rec_emp.sal<1000 then
dbms_output.put_line('员工工资:'||rec_emp.sal||',需加倍努力争取提高工资');
elsif rec_emp.sal>=1000 and rec_emp.sal<2000 then
dbms_output.put_line('员工工资:'||rec_emp.sal||',工资一般,争取搞个部门经理做做');
else
dbms_output.put_line('员工工资:'||rec_emp.sal||',工资不错,争取搞个总经理做做');
end if;
end loop;
end pro_cur;
end pack_emp;
调用程序包中的过程以调用程序包中的游标
exec pack_emp.pro_cur;
示例10:存储过程返回游标的子程序包(此程序包返回r_cur游标)
CREATE OR REPLACE package SCOTT.pk_wt is type mytype is ref cursor; procedure p_wt(mycs out mytype); end; CREATE OR REPLACE package BODY SCOTT.pk_wt is procedure p_wt(mycs out mytype) is r_cur mytype; begin open r_cur for select * from emp; mycs:=r_cur; end p_wt; end pk_wt;
查询有关过程、函数和程序包的信息:USER_OBJECTS数据字典视图
column object_name format a18
select object_name,object_type from user_objects where object_type in ('PROCEDURE','FUNCTION','PACKAGE','PACKAGE BODY');