|
自定义函数:用户自定义函数(user-defined function,UDF)是一种对MySQL扩展的途径,其用法与内置函数相同。
必要条件:参数和返回值;
创建自定义函数:
CREATE FUNCTION func_name RETURNS {STRING | INTEGER | REAL | DECIMAL} routine_body;
函数体:
1、函数体由合法的SQL语句构成;
2、函数体可以是简单的SELECT或者INSERT语句;
3、函数体如果为复合结构则使用BEGIN....END语句;
4、复合结构可以包含声明,循环,控制结构;
mysql> create function f1() returns varchar(30)
-> return date_format(now(),'%y年%m月%d日');
ERROR 1418 (HY000): 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)
mysql> SET GLOBAL log_bin_trust_function_creators = 1;
Query OK, 0 rows affected (0.01 sec)
mysql> create function f1() returns varchar(30)
-> return date_format(now(),'%y年%m月%d日');
Query OK, 0 rows affected (0.07 sec)
mysql> select f1();
+-----------------+
| f1() |
+-----------------+
| 18年11月29日 |
+-----------------+
1 row in set, 1 warning (0.01 sec)
mysql>
创建带参函数:
mysql> create function mount(num1 smallint unsigned,num2 smallint unsigned)
-> returns float(10,2) unsigned
-> return (num1+num2)/2;
Query OK, 0 rows affected (0.08 sec)
mysql> select mount(2,3);
+------------+
| mount(2,3) |
+------------+
| 2.50 |
+------------+
1 row in set (0.00 sec)
mysql>
修改mysql结束符号:
mysql> delimiter //
创建具有复合结构函数体的函数:
mysql> delimiter //
mysql> create function adduser(name varchar(20),id smallint unsigned)
-> returns int unsigned
-> begin
-> insert goods_types(type_name,parent_id) values(name,id);
-> return last_insert_id();
-> end;//
Query OK, 0 rows affected (0.09 sec)
mysql> select adduser('风清扬',3);
-> //
+------------------------+
| adduser('风清扬',3) |
+------------------------+
| 9 |
+------------------------+
1 row in set, 1 warning (0.10 sec)
mysql> select adduser('小龙女',3);//
+------------------------+
| adduser('小龙女',3) |
+------------------------+
| 10 |
+------------------------+
1 row in set (0.01 sec)
mysql> select * from goods_types;
-> //
+---------+-----------------+-----------+
| type_id | type_name | parent_id |
+---------+-----------------+-----------+
| 1 | 家用电器 | 0 |
| 2 | 电风扇 | 1 |
| 3 | 洗衣机 | 1 |
| 4 | 彩电 | 1 |
| 5 | 电脑 | 0 |
| 6 | 笔记本电脑 | 5 |
| 7 | 台式电脑 | 5 |
| 8 | nihao | 3 |
| 9 | 风清扬 | 3 |
| 10 | 小龙女 | 3 |
+---------+-----------------+-----------+
10 rows in set (0.00 sec)
mysql>
删除函数:
DROP FUNCTION [IF EXISTS] func_name; |