存储函数

存储函数

  • 创建无参存储函数get_name,有返回值
    语法:
create or replace function 函数名  return 返回类型 as PLSQL程序段
create or replace function get_name return varchar2
as
begin
  return'哈哈';
end;
  • 删除存储函数getName
    语法:
drop function 函数名
  • 调用存储方式一,PLSQL程序
declare 
  name varchar2(10);
begin
  name:=get_name;
  dbms_output.put_line('姓名是:'||name);
end;
  • 调用存储方式二,java程序
    创建由有参存储函数findEmpIncome(编号),查询7499号员工的年收入,演示in的用法,默认in
--定义函数
create  or replace function findEmpIncome(p_empno emp.empno%type) return number
as
 income number;
begin
 select sal*12 into income from emp where empno=p_empno;
 return income;
end;

--调用函数
declare 
 income number;
begin
 income:=findEmpIncome(7499);
   dbms_output.put_line('该员工年收入为:'||income);
end;
--创建有参存储函数findEmpNameAndJobAndSal(编号),查询7499号员工的姓名(return),职位(out),月薪(out),返回多个值
--创建函数
create or replace function findEmpNameAndJobAndSal(p_empno in number,p_job out varchar2,p_sal out number)
return varchar2
as
  p_ename emp.ename%type;
begin
  select ename,job,sal into p_ename,p_job,p_sal from emp where empno=p_empno;
  return p_ename;
end;
--调用函数
declare 
p_ename emp.ename%type;
p_job emp.job%type;
p_sal emp.sal%type;
val varchar2(255);
begin
  val:= findEmpNameAndJobAndSal(7499,p_job,p_sal);
  dbms_output.put_line('7499'||p_ename||'----'||p_job||'----'||p_sal);
end;

存储过程:无返回值或者有多个返回值时,适合用过程。
存储函数:有且只有一个返回值时,适合用函数。
适合使用过程函数的情况:

  1. 需要长期保存在数据库中。
  2. 需要被多个用户同时使用。
  3. 批操作大量数据,例如批插入多条数据。

适合使用SQL的情况:

  1. 凡是上述反面,都可使用SQL。
  2. 对表、视图、序列、索引等这些,适合用SQL。

向emp表中插入999条记录,写成过程的形式。

--创建过程
create or replace procedure   batchInsert
as
  i number(4):=1;
begin
  for i in 1..999
  loop
    insert into emp(empno,ename) values (i,'测试');
  end loop;
end;
--调用过程
exec batchInsert;

函数版本的个人所得税

create or replace function getrax(sal in number,rax out number) return number
as
  --sal表示收入
  --bal表示需要缴税的收入
  bal number;
begin
  bal:=sal-3500;
  if bal<=1500 then
    rax:=bal*0.03-0;
  elsif bal<4500 then
    rax:=bal*0.1-105;
  elsif bal<9000 then
    rax:=bal*0.2-555;
  elsif bal<35000 then
    rax:=bal*0.3-2775;
  elsif bal<80000 then
    rax:=bal*0.45-5505;
  else
    rax:=bal*0.45-13505;
  end if;
  return bal;
end;
--调用过程
declare
  rax number;
  who number;
begin
  who:=getrax(&sal,rax);
  dbms_output.put_line('您需要交的税'||rax);
end;

你可能感兴趣的:(存储函数)