MySQL8.0自定义函数

    技术2022-07-31  75

    问题简介

    [Err] 1418 - 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)

    [Err] 1418-此函数中没有声明DETERMINISTIC,NO SQL或READS SQL DATA,只用声明才会启用二进制日志记录(您可能想使用不太安全的log_bin_trust_function_creators变量)

    解决办法

    第一种办法,需要声明DETERMINISTIC,NO SQL或READS SQL DATA的一种

    第二种办法,信任子程序的创建者,设置变量log_bin_trust_function_creators值为1

    -- 查看该参数,默认为0 select @@log_bin_trust_function_creators; -- 设置为1 set GLOBAL log_bin_trust_function_creators=1;

    使用样例

    函数声明NO SQL -- mysql中创建一个自定义函数 delimiter $$ create function fun_addnum() -- 注意是returns而不是return returns int NO SQL begin set @i=0; add_num:LOOP set @i=@i+1; -- leave用于跳出循环 if @i=10 then leave add_num; -- iterate跳过后面语句进入下一循环 elseif mod(@i,2)=0 then iterate add_num; end if; -- 结束循环 end loop add_num; return @i; end $$ delimiter ; select fun_addnum(); 函数声明DETERMINISTIC,表示该函数在每次为其参数调用相同值时都返回相同的结果值 delimiter $$ create function fun_hello(x int) returns int DETERMINISTIC comment '这是注释' begin declare i int default 1; declare j int default 10; case x when i then set x=i; when j then set x=j; else set x=i+j; end CASE; return x; end $$ delimiter ; select fun_hello(2); 设置变量log_bin_trust_function_creators的方式 -- 设置为1,此时才可以使用 CONTAINS SQL,MODIFIES SQL DATA set GLOBAL log_bin_trust_function_creators=1; delimiter $$ create function fun_temp() returns int -- READS SQL DATA MODIFIES SQL DATA begin declare cnt int default 0; repeat set cnt=cnt+1; until cnt=10 end repeat; return cnt; end $$ delimiter ;
    Processed: 0.016, SQL: 9