欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

浅谈mysql 自定义函数

程序员文章站 2024-03-01 10:42:04
因为工作需要,要写一个mysql的自定义行数,如下 delimiter $$ drop function if exists `onlinefunction`$...

因为工作需要,要写一个mysql的自定义行数,如下

delimiter $$
drop function if exists `onlinefunction`$$
create function `onlinefunction`(rrrr varchar(50)) returns varchar(255)
begin
if(rrrr='online') then return '上线';end if;
end$$
delimiter ;

第一行delimiter 定义一个结束标识符,因为mysql默认是以分号作为sql语句的结束符的,而函数体内部要用到分号,所以会跟默认的sql结束符发生冲突,所以需要先定义一个其他的符号作为sql的结束符。没有加这个定义的话...

错误码: 1064
you have an error in your sql syntax; check the manual that corresponds to your mysql server version for the right syntax to use near 'end' at line 1

第二行是删除同名的类,不然会...

错误码: 1304
function onlinefunction already exists

第三行第一函数名,函数变量,和返回类型

第四行begin是起始,与end$$对应

第五行是if判断语句,格式为

if(...) then
....;
elseif
....;
else
.....;
end if;
return ..;

有时候mysql不能建立自定义函数是因为该功能2未开启

输入 show variables like '%func%'; 命令

会看到 log_bin_trust_function_creators 的状态,如果是off表示自定义函数功能是关闭的

输入命令 set global log_bin_trust_function_creators=1;

可将 log_bin_trust_function_creators 开启自定义函数功能

但是这样设置是一个临时的方案,因为mysql自动重启后状态又会变为off,所以需要在

在服务启动时加上 “--log-bin-trust-function-creators=1 ”参数。
或在my.ini(my.cnf)中的[mysqld]区段中加上 log-bin-trust-function-creators=1。