自定义函数

1.概念

含义:一组预先编译好的sql语句的集合
好处:
  提高代码的重用性
  简化操作
减少了编译次数并且减少了和数据库服务器的连接次数,提高了效率
区别:
  存储过程:可以有0个返回,也可以有多个返回,适合做批量插入,批量更新
  函数:有且仅有1个返回,适合做处理数据后返回一个结果

2.函数的创建

创建语法:
  create function 函数名(参数列表) returns 返回类型
  begin
    函数体
  end
注意:
  1.参数列表包含两部分:参数名,参数类型
  2.函数体:肯定有return语句,如果没有会报错。
  3.函数体中仅有一句话,则可以省略begin and
  4.使用delimiter语句设置结束标记

3.调用语法

select 函数名(参数列表)

4.各种案例

#当创建函数时报"This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)"
这个意思是,在function里面,只有 DETERMINISTIC, NO SQL 和 READS SQL DATA 被支持。如果我们开启了 bin-log, 我们就必须为我们的function指定一个参数。
可以进行设置一下
set global log_bin_trust_function_creators=TRUE;
这样设置后还要修改一下配置文件,在配置文件中添加
log_bin_trust_function_creators=1

#1.无参有返回
#案例:返回公司的员工个数
use myemployees;
delimiter $
create function myf1() returns int
begin
    declare c int default 0;#定义变量
    select count(1) into c
    from employees;
    return c;
end $
select myf1();
#2.有参有返回
#案例1:根据员工名,返回它的工资
delimiter $
create function myf2(empName varchar(20)) returns double
begin
    set @sal=0;
    select salary into @sal
    from employees
    where last_name=empName;
    return @sal;
end $
select myf2("kochhar");
#案例2:根据部门名,返回该部门的平均工资
delimiter $
create function myf3(deptName varchar(20)) returns  double
begin
    declare sal double;
    select  avg(salary) into sal
    from employees e
    join  departments d on e.department_id=d.department_id
    where d.department_name=deptName;
    return sal;
end $
select myf3("IT");
View Code

5.查看函数

show function status; 
show create function myf3;
View Code

6.删除函数

drop function myf3;
View Code

7.自定函数与存储过程的区别

存储过程实现的过程要复杂一些,而函数的针对性较强;
存储过程可以有多个返回值,而自定义函数只有一个返回值;
存储过程一般独立的来执行,而函数往往是作为其他SQL语句的一部分来使用;
存储过程可以调用函数,但函数不能调用存储过程;

原文地址:https://www.cnblogs.com/xufengnian/p/11872090.html