天天看点

【转】MYSQL入门学习之十三:自定义函数的基本操作

转载地址:http://www.2cto.com/database/201212/177382.html

一、自定义函数(udf)的特性和功能  www.2cto.com  

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

        可以定义一次作用于一行的简单函数,或作用于多行的组的集合函数;

二、基本操作

1、创建自定义函数

        create [aggregate] function function_name

returns {string|integer|real}

        begin

            //函数实现的语句

        end;

        aggregate 指定创建的函数是普通的自定义函数,还是aggregate函数。

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

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

每次服务器启动的时候会重新加载所有有效函数,除非使用--skip-grant-tables参数启动d。在这种情况下, 将跳过udf的初始化,udf不可用。

一个aggregate函数就像一个mysql固有的集合(总和)函数一样起作用,比如,sum或count()函数。要使得aggregate

起作用,mysql.func表必须包括一个type列。如果mysql.func表没有这一

列,则应该运行mysql_fix_privilege_tables脚本来创建此列。

        示例:

[sql] 

mysql> delimiter //  

mysql> create function fun_add_rand(  

    ->     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;  

    -> //  

mysql> delimiter ;  

2、使用自定义函数

mysql> select id from test_inn;  

 +------+  

 | id   |  

 |    1 |  

 mysql> select fun_add_rand(id) from test_inn;  

 +------------------+  

 | fun_add_rand(id) |  

 |               91 |  

 |               34 |  

 |               93 |  

 |               66 |  

3、删除自定义函数

        drop function [ if exists ]

function_name;

mysql> drop function if exists fun_add_rand;  

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

        show create funtion function_name;

mysql> show create function fun_add_rand;        

+--------------+----------+-----------------------------------------------------------+----------------------+----------------------+--------------------+

| function     | sql_mode | create function      

              | character_set_client |

collation_connection | database collation |  

| fun_add_rand |          | create

definer=`root`@`localhost` function `fun_add_rand`(        

    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 | latin1               |

latin1_swedish_ci    | latin1_swedish_ci  |      

5、查看自定义函数状态

        show function status [ like ‘‘ ];

mysql> show function status like ‘fun%‘;  

+------+--------------+----------+----------------+---------------------+---------------------+---------------+

| db   | name         | type     |

definer        | modified          

 | created             | security_type |

| test | fun_add_rand | function | root@localhost | 2012-12-18 20:08:50 |

2012-12-18 20:08:50 | definer       |  

+------+--------------+----------+----------------+---------------------+---------------------+---------------+