【MySql】3.1 自定义函数的使用

1、自定义函数(UDF)的特性和功能mysql

函数能返回字符串,整数或实数;sql

能够定义一次做用于一行的简单函数,或做用于多行的组的集合函数;服务器

2、基本操做

1、建立自定义函数

CREATE [AGGREGATE]FUNCTION function_name RETURNS {STRING|INTEGER|REAL}ide

BEGIN函数

//函数实现的语句spa

END;ip

aggregate 指定建立的函数是普通的自定义函数,仍是AGGREGATE函数。ci

function_name 是用在SQL声明中以备调用的函数名字。字符串

RETURNS 子句说明函数返回值的类型。it

   每次服务器启动的时候会从新加载全部有效函数,除非使用--skip-grant-tables参数启动mysqld。在这种状况下,将跳过UDF的初始化,UDF不可用。

   一个AGGREGATE函数就像一个MySQL固有的集合(总和)函数同样起做用,好比,SUMCOUNT()函数。要使得AGGREGATE 起做用,mysql.func表必须包括一个type列。若是mysql.func表没有这一列,则应该运行mysql_fix_privilege_tables脚原本建立此列。

建立一个自定义函数:将传递进来的值加上1~100的随机数做为返回值返回

delimiter //

create function fun_add_round(in_int int)

  returns int

  BEGIN

     declare i_rand int;

     declare i_return int;

     set i_rand=floor(rand()*100);

     set i_return=in_int+i_rand;

     return i_return;

  END

delimiter ;

2、使用自定义函数

mysql> select quantity from t_goods;
+----------+
| quantity |
+----------+
|       50 |
|       43 |
|       54 |
+----------+

mysql> select fun_add_round(quantity) from t_goods;
+-------------------------+
| fun_add_round(quantity) |
+-------------------------+
|                      78 |
|                      98 |
|                     147 |  每个增长的值都不同
+-------------------------+

3、删除自定义函数

DROP FUNCTION [ IF EXISTS ] function_name;

drop function if exists fun_add_round;

4、查看自定义函数建立信息

SHOW CREATE FUNTION function_name;

mysql> show create function fun_add_round\G
*************************** 1. row ***************************
           Function: fun_add_round
           sql_mode: STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
    Create Function: CREATE DEFINER=`root`@`localhost` FUNCTION `fun_add_round`(in_int int) RETURNS int(11)
BEGIN
 declare i_rand int;
 declare i_return int;

 set i_rand=floor(rand()*100);
 set i_return=in_int+i_rand;

 return i_return;
END
character_set_client: utf8
collation_connection: utf8_general_ci
Database Collation: utf8_general_ci

5、查看自定义函数状态

show function status like 'fun%';

mysql> show function status like 'fun%'\G*************************** 1. row ***************************                  Db: mydata                Name: fun_add_round                Type: FUNCTION             Definer: root@localhost            Modified: 2014-04-09 14:35:15             Created: 2014-04-09 14:35:15       Security_type: DEFINER             Comment:character_set_client: utf8collation_connection: utf8_general_ci  Database Collation: utf8_general_ci

相关文章
相关标签/搜索