開發中常遇到 CREATE FUNCTION 失敗,本文總結三類典型錯誤及修復方法。
錯誤:
Error Code: 1227. Access denied; you need (at least one of) the SUPER privilege(s) for this operation
排查:
-- 檢查是否開啟函數創建權限 SHOW VARIABLES LIKE '%func%'; -- 開啟權限 SET GLOBAL log_bin_trust_function_creators = 1;
真因: SQL 中指定了 DEFINER=`devop`@`%`,但當前實例無此用戶。移除 DEFINER 或改為當前用戶即可。
-- 原問題 SQL CREATE DEFINER=`devop`@`%` FUNCTION `nextval`(...) -- 修正:去掉 DEFINER 或改為 CURRENT_USER CREATE FUNCTION `nextval`(...)
錯誤:
ERROR 1418 (HY000): This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled...
原因: log_bin_trust_function_creators 默認 OFF,啟用 Binlog 時要求函數聲明確定性特性。
解決:
SET GLOBAL log_bin_trust_function_creators = 1; -- 主從架構下,Slave 也需執行並重啟複製 STOP SLAVE; SET GLOBAL log_bin_trust_function_creators = 1; START SLAVE;
-- 登錄 MySQL SET GLOBAL log_bin_trust_function_creators = 1; START SLAVE; -- 監控錯誤日志確認 Slave 正常運行
my.cnf 永久設置 log_bin_trust_function_creators=1。DETERMINISTIC 或 READS SQL DATA,提高代碼可移植性。