MySQL自定义函数

原文连接http://zhhll.icu/2021/01/03/%E6%95%B0%E6%8D%AE%E5%BA%93/%E5%85%B3%E7%B3%BB%E5%9E%8B%E6%95%B0%E6%8D%AE%E5%BA%93/MySQL/MySQL%E8%87%AA%E5%AE%9A%E4%B9%89%E5%87%BD%E6%95%B0/mysql

MySQL自定义函数

函数与存储过程相似,也是一组预先编译好的SQL语句的集合,可是存储过程能够有0个或多个返回,函数就只能有一个返回sql

建立函数

#语法 参数列表包含两部分 参数名和参数类型
#函数体必须有return语句 且每一个sql语句后要以;结尾 因此须要使用delimiter来从新设置结束标记
#函数体中只有一句话时能够省略begin end
create function 函数名(参数列表) returns 返回值类型
begin
	函数体
end

执行函数

select 函数名(参数列表)

查看函数

show create function 函数名;

删除函数

drop function 函数名;

示例

delimiter $

create function myfunc(class_name varchar(20)) returns int
begin 
	declare c int default 0; #设置局部变量,做为返回值
	select count(s.id) into c # 将查询结果赋给局部变量
  from class c
  join student s on c.id = s.classid
  where c.name = class_name;
  return c; #返回
end $

delimiter ;
select myfunc('计算机一班');#函数调用

特别提醒一下:我在建立函数的时候出错了less

ERROR 1418 (HY000): 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)函数

须要设置一下code

set global log_bin_trust_function_creators=TRUE;

因为自己的博客百度没有收录,博客地址http://zhhll.icuget

相关文章
相关标签/搜索