Oracle_PL/SQL 存储过程

来源:互联网 发布:java内部类例子 编辑:程序博客网 时间:2024/06/06 01:10

1.Oracle 提供可以吧PL/SQL程序存储在数据库中,并且可以在任何地方来运用它。这样就叫存储过程或者函数。


2.创建函数

例:返回helloworld的函数,is相当于declare用于声明局部变量,第一个return只声明返回类型

create or replace function hello_worldreturn vaarchar2isbeginreturn 'helloworld';end;


调用该函数

select  hello_world from dual;

例2:创建带参数的函数

create or replace function hello_world(v_logo varchar2)return varchar2isbeginreturn 'helloworld'||v_logo;endl;
调用该函数

select  hello_world('testLogo') from dual;

例3:返回当前系统时间的存储函数

create or replace funtion get_sysdatereturn dateisv_date date;beginv_date :=sysdate;return v_date;end;
例4:定义一个函数,获取给定部门的工资总和,要求:部门编号为参数,工资总和为返回值

create or replace funtionc get_sumsal(dept_id number)return numberisv_sumsal number(10) :=0;cursor salary_cursor is select salary from employees where deptment_id=dept_id;beginfor c in salary_cursor loop v_sumsal :=v_sumsal+c.salary;end loop;return  v_sumsal;end;


3.关于OUT型的参数

因为函数只能有一个返回值,PL/SQL程序可以通过OUT型的参数实现有多个返回值。

例:定义一个函数,获取给定部门的工资总和,要求:部门编号为参数,工资总和为返回值,员工总数用OUT类型

create or replace funtionc get_sumsal(dept_id numbertotal_count out number)return numberisv_sumsal number(10) :=0;cursor salary_cursor is select salary from employees where deptment_id=dept_id;begintotal_count :=0;for c in salary_cursor loopv_sumsal :=v_sumsal+c.salary;total_count :=total_count+1;end loop;return  v_sumsal;end;

调用该函数: 使用plsql调用,创建v_num变量,引入out位置。函数会在执行中赋值。

declarev_num number(5);begindbms_output.out_line(get_sumsal(80,v_num));dbms_output.out_line(v_num);end;





0 0