CREATE FUNCTION function_nameRETURNS{STRING|INTEGER|REAL|DECIMAL} routine_body
mysql> CREATE FUNCTION f1() RETURNS VARCHAR(30) -> RETURN DATE_FORMAT(NOW(),'%Y年%m月%d日 %H点:%i分:%s秒'); Query OK, 0 rows affected (0.00 sec) mysql> SELECT f1();+-------------------------------------+| f1() |+-------------------------------------+| 2016年11月28日 08点:34分:55秒 |+-------------------------------------+
mysql> CREATE FUNCTION f2(num1 SMALLINT UNSIGNED,num2 SMALLINT UNSIGNED) -> RETURNS FLOAT(10,2) UNSIGNED -> RETURN (num1+num2)/2; Query OK, 0 rows affected (0.00 sec) mysql> SELECT f2(10,16);+-----------+| f2(10,16) |+-----------+| 13.00 |+-----------+
DROP FUNCTION [IF EXISTS] function_name
mysql> DELIMITER //mysql> CREATE FUNCTION adduser(username VARCHAR(20)) -> RETURNS INT UNSIGNED -> BEGIN -> INSERT test(username) VALUES(username); -> RETURN LAST_INSERT_ID(); -> END -> // mysql> DELIMITER ; mysql> SELECT adduser('Tom');+----------------+| adduser('Tom') |+----------------+| 3 |+----------------+ mysql> SELECT adduser('Rool');+-----------------+| adduser('Rool') |+-----------------+| 4 |+-----------------+ mysql> SELECT * FROM user;+----+----------+| id | username |+----+----------+| 1 | Drive || 2 | Cve || 3 | Tom || 4 | Rool |+----+----------+
本文转自谢育政 51CTO博客,原文链接:http://blog.51cto.com/kurolz/1929135,如需转载请自行联系原作者