现在的位置: 首页 > 综合 > 正文

数据库之函数

2012年12月26日 ⁄ 综合 ⁄ 共 932字 ⁄ 字号 评论关闭
函数与过程相似,也是数据库中存储的已命名 PL/SQL 程序块.
函数的主要特性是它必须返回一个值.创建函数时通过 return 子句指定函数返回值的数据类型.

--创建函数格式(创建函数必须指定函数的返回值类型)

create [or replace] function function_name [(parameter1, parameter2...)]
return datatype
{is | as}

begin
Executable_Statements;

Exception_handlers;]
end;

--示例一

create or replace function fun_hello
return varchar2
is
begin
return '朋友,您好';
end;
/

select fun_hello from dual;  --执行函数

--示例二

create or replace function emp_price_range(sal number)
return varchar2
as
min_sal number;
max_sal number;
begin
  select min(sal), max(sal) into min_sal, max_sal from emp;
  if sal >= min_sal and sal <= max_sal then
    return '输入的工资介于最低工资与最高工资之间';
  else
    return '超出范围';
  end if;
end;
/

set serveroutput on;
declare
p number := 5500;
msg varchar2(50);
begin
  msg := emp_price_range(p);
  dbms_output.put_line(msg);
end;
/

/*
declare
msg varchar2(50);
begin
  msg := emp_price_range(&p);
  dbms_output.put_line(msg);
end;
*/

--函数授权

grant execute on fun_hello to martin;

grant execute on fun_hello to public;

--删除函数

格式: drop function function_name;

示例:drop function fun_hello;

【上篇】
【下篇】

抱歉!评论已关闭.