【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

相關文章
相關標籤/搜索