在oracle中,函数和存储过程是经常使用到的,他们的语法中有很多相似的地方,但也有自己的特点。刚学完函数和存储过程,下面来和大家分享一下自己总结的关于函数和存储过程的区别。
存储过程是存储在数据库中提供所有用户程序调用的子程序,定义存储过程的关键字为procedure。
1 2 3 4 5 6 7 |
create [or replace] procedure 存储过程名 [(参数1 类型,参数2 out 类型……)] as 变量名 类型; begin 程序代码体 end; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
create or replace procedure p1 --or replace代表创建该存储过程时,若存储名存在,则替换原存储过程,重新创建 --无参数列表时,不需要写() as begin dbms_output.put_line('hello world'); end; --执行存储过程方式1 set serveroutput on; begin p1(); end; --执行存储过程方式2 set serveroutput on; execute p1(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
create or replace procedure p2 (name in varchar2,age int,msg out varchar2) --参数列表中,声明变量类型时切记不能写大小,只写类型名即可,例如参数列表中的name变量的声明 --参数列表中,输入参数用in表示,输出参数用out表示,不写时默认为输入参数。 ------------输入参数不能携带值出去,输出参数不能携带值进来,当既想携带值进来,又想携带值出去,可以用in out as begin msg:='姓名'||name||',年龄'||age; --赋值时除了可以使用:=,还可以用into来实现 --上面子句等价于select '姓名'||name||',年龄'||age into msg from dual; end; --执行存储过程 set serveroutput on; declare msg varchar2(100); begin p2('张三',23,msg); dbms_output.put_line(msg); end; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
create or replace procedure p3 (msg in out varchar2) --当既想携带值进来,又想携带值出去,可以用in out as begin dbms_output.put_line(msg); --输出的为携带进来的值 msg:='我是从存储过程中携带出来的值'; end; --执行存储过程 set serveroutput on; declare msg varchar2(100):='我是从携带进去的值'; begin p3(msg); dbms_output.put_line(msg); end; |
1 2 3 4 5 6 7 8 9 10 11 |
create or replace procedure p4 as --存储过程中定义的参数列表 name varchar(50); begin name := 'hello world'; dbms_output.put_line(name); end; ---执行存储过程 set serveroutput on; execute p4(); |
存储过程虽然有很多优点,但是它却不能使用return返回值。当需要使用return返回值时,我们可以使用函数。
1.函数与存储过程的结构类似,但是函数必须有一个return子句,用于返回函数值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
create or replace function f1 return varchar--必须有返回值,且声明返回值类型时不需要加大小 as msg varchar(50); begin msg := 'hello world'; return msg; end; --执行函数方式1 select f1() from dual; --执行函数方式2 set serveroutput on; begin dbms_output.put_line(f1()); end; |
如果只有一个返回值,用存储函数,否则,一般用存储过程。
好教程 赞
2017年4月11日 下午1:24