mysql之函数总结

先讲一下mysql函数的含义:

一组预先编译好的sql语句的集合,理解成批处理语句

使用函数的目的:

1、提高代码的重用性

2、简化操作

3、减少了编译次数并且减少了和数据库服务器的连接次熟,提高了效率。

函数和存储过程的区别:

存储过程:可以有0个返回值,也可以有多个返回值,适合做批量插入,批量更新

函数:有且只有一个返回值,适合做处理数据后返回一个结果。

一、创建语法:

create  function  函数名(参数列表) return是返回类型

begin

函数体

end


#注意
1、参数列表包含两部分:参数名,参数类型
2、函数体:肯定会有return语句,如果没有会报错,如果return语句没有放在函数体的最后也不报错,但是不建议(没有意义)
3、函数体中仅有一句话,可以省略begin end
4、使用delimiter语句设置结束标记(demilter $)

二、调用语法

select  函数名(参数列表)

示例:

1、无参有返回

返回公司的员工个数

create function myf1()returns int

begin  

    declare c int default 0;
    select count(*) into c
    from employees;
    return c;

end $


select myf1()$

有参有返回

#根据员工名返回工资

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('king') $

根据部门名返回该部门的平均工资

create function myf3(repName 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 =repName; 
    return sal;
end $ 
 
select myf3('IT') $

三、查看函数

show create function 函数名;

四、删除函数

drop function 函数名

猜你喜欢

转载自blog.csdn.net/weixin_42575020/article/details/113572156