mysql function summary

Let me talk about the meaning of the mysql function:

A set of pre-compiled SQL statements, understood as batch statements

The purpose of using the function:

1. Improve code reusability

2. Simplify operation

3. Reduce the number of compilations and reduce the number of connections to the database server, which improves efficiency.

The difference between functions and stored procedures :

Stored procedure: There can be 0 return values ​​or multiple return values, suitable for batch insertion and batch update

Function: There is one and only one return value , which is suitable for returning a result after processing the data.

One, create grammar:

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

begin

函数体

end


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

Two, call syntax

select function name (parameter list)

Example:

1. Return without participation

Returns the number of employees in the company

create function myf1()returns int

begin  

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

end $


select myf1()$

Participate and return

#根据员工名返回工资

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

Return the average salary of the department according to the department name

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

Three, view function

show create function function name;

Four, delete function

drop function function name

 

 

Guess you like

Origin blog.csdn.net/weixin_42575020/article/details/113572156