含义:一组预先编译好的sql语句的集合,理解成成批的语句。
1.提高代码的重用性 2.简化操作 3.减少编译次数并且减少和数据库服务器的连接次数,提高效率。
区别:存储过程:可以有0个返回,也可以有多个返回,适合做批量插入,批量更新。
函数:有且只有一个返回,适合做数据处理后返回的一个结果。
1.创建语法
create function 函数名(参数列表) return 返回类型
begin
函数体
end
注意:1.参数列表 包含两部分: 参数名 参数类型
2.函数体:肯定会有return语句,如果没有报错的话 如果return 语句没有放在函数体的最后也不会报错,但是不建议
return 值:3.函数体仅有一句话,则可以省略begin end 4.使用delimiter
调用函数函数;
select 函数名(参数列表);
案例: 返回公司的员工个数
create function myf1() returns int
begin
declare c int default 0; #定义变量
select count(*)into c #f赋值
from employees
return c;
end $
select myf1() $
2.有返回值的
案例:根据员工名字,返回相应工资
create function retusalr(empName(20) returns double
begin
set @sal = 0;
select salary into @sal
from employees
where name = empName;
return @sal;
end $
案例2 根据部门名,返回该部门的平均工资
create function avgsal(dept_name varchar(20) retunrs double
begin
declare avgasl ;
select avg(salary)
from employees e
join department d
on d. departmen_id = e.department_id
where d.department_id = dept_name;
return avgasl;
end $
#调用
select avfsal(2);
前面讲的都是输入一个值,接下来实现传入两个值得,返回二者之和。
create function test_fun(num1 float,num2 float) return float
begin
declare sum float default 0;
set sum = num1+num2;
return sum;
end $
select test_fun(1,2)