oracle函数存储,Oracle存储过程和存储函数

1.存储过程

将一段已经编译好的代码,封装到数据库中

1. 作用 :

提高了代码的复用性

因为以及编译好了,可以提高了执行效率

关键字 - procedure /prə’siːdʒə/ 过程,程序,手续

2. 语法:

create [or replace] procedure

过程名称(参数1 in|out 参数类型,参数2 in|out 参数类型)

is | as

-- 声明

begin

-- 业务

end;

调用方法:

一: call 过程名称(参数);

二: plsql中使用:

begin

过程名称(参数);

end;

1.输入参数

定义一个存储过程,给员工编号为7369的员工涨1000工资

代码实现:

create or replace procedure

update_sal(vempno in number,vcount in number)

is

-- 声明变量记录当前工资

cur_sal number;

begin

-- 先查询涨工资前的工资

select sal into cur_sal from emp where empno = vempno;

dbms_output.put_line('涨工资前: '||cur_sal);

-- 更新工资

update emp set sal = sal + vcount where empno = vempno;

-- 涨工资后的工资

dbms_output.put_line('涨工资后: '||(cur_sal+vcount));

commit;

end;

调用:

call update_sal(7369,1000);

begin

update_sal(7369,1000);

end;

2.输出参数

根据员工编号,得到年薪

create or replace procedure

year_sal(vempno in number,vyearsal out number)

as

begin

select sal*12 + nvl(comm,0) into vyearsal --nvl(a,b) 如果a为null,则取b

from emp where empno = vempno;

end;

调用:

declare

yearsal number;

begin

year_sal(7369,yearsal);

dbms_output.put_line(yearsal);

end;

3.输出的是游标类型:

游标的类型是sys_refcursor

打开游标并获取数据一步合成:

open 游标名 for 查询语句

定义游标:

create or replace procedure

findall_cursor(vcursor out sys_refcursor)

is

begin

--打开游标,指定结果集

open vcursor for select * from emp;

end;

emp%rowtype 指的是emp的行类型

%type可以使变量获得与字段相同的数据类型

调用

declare

yb sys_refcursor;

-- 定义一个vrow变量,类型是emp的行类型

vrow emp%rowtype;

begin

findall_cursor(yb);

loop

fetch yb into vrow;

exit when yb%notfound;

dbms_output.put_line('编号:'||vrow.empno||' 姓名:'||vrow.ename);

end loop;

-- 关闭游标

close yb;

end;

2.存储函数

实质是跟存储过程一样

和存储过程的区别:

函数有返回值,过程没有,函数的返回值可以用:=接收

函数可以直接在sql中调用,过程不能

函数和过程都实现对方的功能.

语法:

create [or replace] function

函数名称(参数1 参数类型) return 返回类型

is

返回变量 变量类型

begin

...

return 返回变量

end;

定义一个存储函数,根据员工编号计算一个月的纳税,税率15%

代码:

create or replace function

fun_getTax(vempno number) return number

is

vtax number;

begin

select sal*0.15 into vtax from emp where empno = vempno;

return vtax;

end;

调用:

declare

vtax number;

begin

vtax := fun_getTax(7369);

dbms_output.put_line(vtax);

end;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值