一、首先查看创建函数的功能是否开启:
mysql> show variables like '%func%';
+-----------------------------------------+-------+
| Variable_name | Value |
+-----------------------------------------+-------+
| log_bin_trust_function_creators | ON |
+-----------------------------------------+-------+
1 row in set (0.02 sec)
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> 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> 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)
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;
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;