用户自定义函数(user-defined function,UDF) 是一种对mysql的扩展途径,其用法与内置函数相同
创建自定义函数
语法
create function function_name
returns
{string|integer|real|decimal}
routine_body
Example1
delimiter $
create function f1(gdate datetime)
returns varchar(100) READS SQL DATA -- 一定要声明;
begindeclare x varchar(100) default '';set x = date_format(gdate,'%Y年%m月%h日 %H时%m分%s秒');return x;
end $
delimiter ;
Example2
delimiter $
create function str_cut(str varchar(255),length tinyint)
returns varchar(255) READS SQL DATA
beginif(ISNULL(str)) then return '';elseif char_length(str) <= length thenreturn str;elseif char_length(str) > length thenreturn contact(left(str,length),'...');end if;
end $
delimiter ;
查看函数
mysql> show function statusG
*************************** 1. row ***************************Db: testName: f1Type: FUNCTIONDefiner: root@localhostModified: 2015-05-01 16:21:40Created: 2015-05-01 16:21:40Security_type: DEFINERComment:
character_set_client: utf8
collation_connection: utf8_general_ciDatabase Collation: latin1_swedish_ci
删除函数
mysql> drop function f1; -- f1 函数名;
Query OK, 0 rows affected