存储过程和存储函数
指存储在数据库中共所有用户程序调用的子程序(plsql)叫做存储过程,存储函数
存储函数和存储过程的区别是,存储函数可以通过return 返回一个函数值, 但是存储过程不可以,一个有返回值, 一个没有返回值
创建存储过程
create procedure 命令创建存储过程
create[or replace ] procedure 过程名 (参数列表)
as /is
plsql 子程序体
把Oracle 跳出默认输出模式用这个sql语句
调用存储过程
exec 存储过程名字 这里是一个sqlplus 语句 调用一次
可以在另一个plsql 中进行调用, begin 开始, end 结尾
下面我们就写一个存储过程
Hello World
create or replace procedure hello as begin dbms_output.put_line('Hello world') ; end ; -- 调用存储过程 --1 . 调用一次 exec hello() ; -- 2. 调用多次 begin hello (); hello() ; end ;带参数的存储过程
一般在存储过程中提交回滚,让调用者 提交, 这样可以保重是同一个事物
存储过程的参数要加 in out 标识是输入输出的参数
-- 给指定的员工张一白工资, 并且打印涨前涨后的工资 create or replace procedure raiseSalary(eno in number) is -- 定义变量 存储涨前的工资 psal emp.sal%type ; begin -- 查询员工涨前粽子 select sal into psal from emp where empno=eno ; -- 给工资涨100 块钱 update emp set sal=sal+100 where empno=eno; -- 执行了更新操作, 要不要 commit? ? 这里不要一般不要再存储过程总共使用事物, 因为要保障调用者和 -- 这个子程序实在一个事物之内 -- 打印 涨后的工资和涨前的工资 dbms_output.put_line('涨前'||psal ||'涨后' || (psal+100)); end raiseSalary; -- 调用存储过程 exce reisesalary(9851); -- 多次调用 begin exce reisesalary(2565); exce reisesalary (1215) end;
多个参数的存储过程
-- 给指定的员工涨指定的工资然后打印 create or replace procedure raisesalary2(eno in number , psal in number) is psal_out emp.sal%type ; begin -- 查询员工的钱 select sal into psal_out from emp where empno=eno ; -- 更新操错 update emp set sal=sal+psal where empno=eno ; -- 打印 dbms_output.put_line('员工号'|| eno || '涨了工资' ||psal_out+psal); end raisesalary2;存储函数(Function)
为一个命名的存储程序,可带参数, 并返回计算值,函数和过程的结构类似但是必须要有一个return字句
语法 :
create or replace function 函数名字(参数)
return 函数值类型
as
plsql 程序
查询员工的年收入
-- 查询员工年收入 create or replace function queryEmopIncome(eno in number) return number is -- 定义保存年薪和月薪的值 psal emp.sal%type ; pcomm emp.comm%type ; begin -- 得到月薪和奖金 select sal,comm into psal,pcomm from emp where empno=eno ; -- 返回年收入 return psal*12+nvl(pcomm,0) ; -- 缕空函数 end queryEmopIncome;
过程函数中的out in ;
函数和过程的区别主要是有没有返回值,但是过程可以通过out 输出多个值,
如果有一个返回值就用函数, 如果没有返回值,和多个返回值, 就用过程
存储过程能代替存储函数,为什么还要保留存储函数 ?
向下兼容, 老版本实用
java 不能调用plsql 但是java可以调用存储过程, 存储函数