首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

MySQL 儲存程序匯出避坑指南:mysqldump 參數組合、Trigger 衝突與函數創建權限

     編輯:MySQL 資料庫相關知識

場景:部署時發現儲存程序缺失

錯誤:FUNCTION config_get does not exist。檢查 SHOW PROCEDURE STATUS 為空 → 匯出時未包含儲存程序。

正確匯出指令(僅程式碼,無結構無資料)

mysqldump -u user -p -n -t -d -R dbname > routines.sql
# -n (--no-data)       不導資料
# -t (--no-create-info) 不導 CREATE TABLE
# -d (--no-create-db)   不導 CREATE DATABASE
# -R (--routines)       導出 FUNCTION/PROCEDURE

陷阱 1:Trigger 衝突報錯

ERROR 1235 (42000): This version of MySQL doesn't yet support
'multiple triggers with the same action time and event for one table'

原因:-R 會連帶匯出 Trigger,若目標庫已存在同名 Trigger → 衝突。

解決:顯式關閉 Trigger 匯出

mysqldump -u user -p -n -t -d -R --triggers=false dbname > routines.sql

陷阱 2:函數創建權限報錯

Error Code: 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)

原因:啟用 Binlog 時,創建函數需聲明確定性/無副作用,否則複寫不安全。

解決:/etc/my.cnf [mysqld] 區段添加

log_bin_trust_function_creators = 1

重啟 MySQL 生效。或修改函數定義添加 DETERMINISTIC/READS SQL DATA(推薦)。

完整匯入流程

# 1. 修改配置
echo "log_bin_trust_function_creators = 1" >> /etc/my.cnf
systemctl restart mysqld

# 2. 匯入儲存程序
mysql -u user -p dbname < routines.sql

# 3. 驗證
mysql -u user -p -e "SHOW PROCEDURE STATUS WHERE Db='dbname';"
mysql -u user -p -e "SHOW FUNCTION STATUS WHERE Db='dbname';"

最佳實踐建議

  • 儲存程序/函數**單獨版本控制**(Git),不混雜在完整備份中
  • 部署腳本按順序:結構 → 程式碼 → 資料
  • 函數定義**強制聲明** DETERMINISTIC / NO SQL / READS SQL DATA / MODIFIES SQL DATA
  • 複寫環境下,**主庫創建函數自動同步到從庫**,勿重複執行
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved