MySql創建函數

一、首先查看創建函數的功能是否開啓:
mysql> show variables like '%func%';
+-----------------------------------------+-------+
| Variable_name | Value |
+-----------------------------------------+-------+
| log_bin_trust_function_creators | ON    |
+-----------------------------------------+-------+
1 row in set (0.02 sec)

二、如果Value處值爲OFF,則需將其開啓。
mysql> set global log_bin_trust_function_creators=1;

三、創建函數時,先選擇數據庫,
mysql> use xxx;
Database changed

delimiter 爲命令終止符號,代替分號,因爲分號在begin...end中會用到;
mysql> delimiter //
CREATE FUNCTION first_func(param INT)
RETURNS INT
BEGIN
   DECLARE @result INT DEFAULT 2  ;
   DECLARE @bRet INT ;
   SET @bRet= @result + param ;
   RETURN @bRet ;
END ;
//
函數創建成功後需恢復分號爲命令終止符號。
mysql> delimiter ;

四、測試:
mysql> select first_func(5);
+-------------------------------+
| first_func(5) |
+-------------------------------+
|                             1 |
+-------------------------------+
1 row in set (0.47 sec)

五、刪除函數:
mysql> drop function first_func ;
Query OK, 0 rows affected (0.11 sec)

六、查看函數
1) show function status
顯示數據庫中所有函數的基本信息
2)查看某個具體函數
mysql>show create function first_func;

七、注意
使用into的方法(單個賦值) select id into @id from user where id= _id;
多個賦值 select id,name into @id, @name from user where id= _id;


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章