子程序
- 子程序是命名的PL/SQL块,可带参数并可在需要时随时调用
- PL/SQL有两种类型的子程序,即过程和函数
- 过程用于执行特定的任务,函数用于执行任务并返回值
过程
--过程
create [or replace] procedure 过程名[(参数列表)]
is/as
--声明部分
begin
--可执行部分
--[异常部分]
end [过程名];
- or replace 是可选的,表示当前用户下已存在同名的存储过程,则覆盖旧的存储过程;参数可有可无,无参数不写小括号.
- is as 标志PL/SQL块的开始,两者等价.
参数模式
调用程序是通过参数向存储过程传值的,存储过程中的行参接收调用者传递过来的参数,并进行操作.
参数名称 [in | out | in out] 数据类型
in : 默认模式,表示参数只能由外界输入,不能在存储过程中改变参数的值.
out : 表示该参数在存储过程进行赋值,可以返回;参数不能使用常量
in out : 具有in out 的共有特征.
无参过程
--无参过程
create or replace procedure pro_hello
is
hi varchar2(20):='hello world';
begin
dbms_output.put_line(hi);
end pro_hello;
--调用无参过程:PL/SQL
declare
begin
--调用需写小括号!!!
pro_hello();
end;
有参过程:in
--有参过程:in
create or replace procedure pro_1(p in number)--参数只能声明类型 不能指定长度
is
begin
dbms_output.put_line(p);
--p:=10;in模式的参数不能赋值改变
end;
--调用有参过程:in
declare
begin
pro_1(66);
end;
有参过程:out
--有参过程:out
create or replace procedure pro_2(p out number)--参数只能声明类型 不能指定长度
is
i number(10):=66;
begin
p:=i;--赋值改变p的值
end;
--调用有参过程:out
declare
j number(15):=33;
begin
dbms_output.put_line('yesterday:' || j);
pro_2(j);
dbms_output.put_line('tomorrow:' || j);
end;
函数
函数与过程相似,函数主要特征是必须返回一个值
--函数
create [or replace] function 函数名[(参数列表)] return 数据类型
is/as
--声明部分
begin
--可执行部分
--[异常部分]
end [函数名];
--无参函数
create or replace function fun_1 return varchar2 --参数只能声明类型 不能指定长度
as
str varchar2(20):='hello world';
begin
return str;
end fun_1;
--调用无参函数:方式一,PL/SQL
declare
begin
dbms_output.put_line(fun_1());
end;
--调用无参函数:方式二,SQL语句
select fun_1() from dual;
select fun_1 from dual;
--有参函数
create or replace function fun_2(p in number ,q out number) return number --参数只能声明类型 不能指定长度
as
begin
q := 66;--给out模式参数赋值
return p+q;
end;
--调用有参函数:PL/SQL
declare
j number(10):=13;
begin
dbms_output.put_line(fun_2(45 ,j));
dbms_output.put_line(j);
end;
程序包
程序包是一种数据库对象,是对相关存储过程、函数、变量、游标和异常等对象的封装,包括程序包规范和程序包主体
创建包规范
--程序包规范
create or replace package 包名
is/as
[公共类型声明、常量、变量、异常和游标等声明]
[子程序声明 (只包含定义声明,不实现)]
end [包名];
创建包主体
--程序包主体
create or replace package body 包名
is/as
[私有项声明]
--包规范中子程序的实现
[包规范中未声明的私有子程序]
[begin]
[包的初始化语句]
end [包名];
--创建程序包规范
create or replace package my_pack
is
procedure findsalbydeptno(empid number);--过程
function getsal(empid number) return number;--函数
end;
--创建程序包主体
create or replace package body my_pack
as
--过程实现
procedure findsalbydeptno(empid number)
is
nsal emp.sal%type;
begin
select sal into nsal from emp where empno=empid;
dbms_output.put_line(nsal);
end;
--函数实现
function getsal(empid number) return number
is
nsal emp.sal%type;
begin
select sal into nsal from emp where empno=empid;
return nsal;
end;
end;
--程序包调用
declare
begin
my_pack.findsalbydeptno(7788);
dbms_output.put_line(my_pack.getsal(7788));
end;
select my_pack.getsal(7788) from dual;