假設students表中包含id和name兩個字段,建立一個函數,函數的作用是根據id查找name
create table students(id int,name varchar(100)); insert into students(id,name) values(1,'annie'),(2,'bell'),(3,'danny');
DELIMITER // create function find_student(id int) returns varchar(100) READS SQL DATA begin declare sname varchar(100) default ''; select students.name into sname from students where students.id=id; return sname; end // DELIMITER ;
需要注意的事項:
1)使用DELIMITER//修改分隔符號
mysql的預設語句結束符號是分號,當mysql遇到分號時就自動執行目前語句。因為函數定義時包含多個sql語句,所以使用DELIMITER //先將分隔符號設為//,等函數建立語句完成後,再將分隔符號改回分號即可。
2)READS SQL DATA
#my#my#my#my#my#my#my#my#my#my#my#my#my#my#了函式的類型:mysql開啟了bin-log, 我們就必須指定我們的函數是否是哪種類型:之前我沒寫這句話,但是創建時mysql報錯,提示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)#sql
變數定義:我在這裡使用declare sname varchar(100) default ‘ ’;定義了局部變數sname,
##變數使用:
可以使用select students.name into sname from students where students.id=id;為變數賦值
也可以直接使用set語句來賦值,如set sname=‘test’3.執行函數:select 函數名稱(參數值);select find_student(3);
Caused by: java.sql.SQLException: 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 sater logging is enabled (you *might* want to use the less safe log_bin_trustator_function_v # at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:965)
at com.mysql.jdbc.MysqlIO.checkE#orPacket(MyhIO.java:3976) java:3976) checkErrorPacket(MysqlIO.java:3912)at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:871)at com.mysql.bbc.java:871)
at com.mysqlIO.bbc. # at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2739)
at com.mysql.jdbc.ConnectionImpl execSQL(ConnectionImpl.java:2440)
at com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:845)
at com.mysql.bc.java:845)
at com.mysql.bc.javaStatementImpl. # ... 35 more
這是因為有一個安全參數沒有開啟,log_bin_trust_function_creators 預設為0,是不允許function的同步的,開啟這個參數,就可以創建成功了。
查看是否開啟:為on則是開啟了show variables like '%func%'; +---------------------------------+-------+ | Variable_name | Value | +---------------------------------+-------+ | log_bin_trust_function_creators | ON | +---------------------------------+-------+ 1 row in set (0.00 sec)登入後複製
set global log_bin_trust_function_creators = 1;
可以透過這個指令設置,但MySQL重啟後就失效了。
所有最後是透過修改MySQL資料庫的設定檔
在設定檔/etc/my.cnf的[mysqld]設定log_bin_trust_function_creators=1
修改完後重啟MySQL。以上是Mysql中自訂函數的建立和執行方法是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!