您的位置:首页 > 数据库 > MySQL

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

2014-05-09 16:20 831 查看
转载地址: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参数启动mysqld。在这种情况下, 将跳过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、使用自定义函数
示例:
[sql]
mysql> select id from test_inn;
+------+
| id |
+------+
| 1 |
| 1 |
| 1 |
| 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;
示例:
[sql]
mysql> drop function if exists fun_add_rand;

4、查看自定义函数创建信息
SHOW CREATE FUNTION function_name;
示例:
[sql]
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 '' ];
示例:
[sql]
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 |
+------+--------------+----------+----------------+---------------------+---------------------+---------------+
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: