mysql 函数类型(MySQL还能自定义函数)(1)

MySQL自定义函数

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

创建函数

#语法 参数列表包含两部分 参数名和参数类型 #函数体必须有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('计算机一班');#函数调用

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

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 logbintrustfunctioncreators variable)

需要设置一下

set global log_bin_trust_function_creators=TRUE;

,