教程集 www.jiaochengji.com
教程集 >  数据库  >  mysql  >  正文 mysql自定义函数的一个例子

mysql自定义函数的一个例子

发布时间:2015-12-02   编辑:jiaochengji.com
本文介绍一段mysql自定义函数的代码,有需要的朋友参考下吧。

为大家举个例子,一个mysql的自定义函数,代码如下:
 

复制代码 代码示例:

create function testdate(pbirthday date)
returns integer
begin
return year(now()) - year(pbirthday);
end;

select  testdate(birthday)<40 from user;

set global log_bin_trust_function_creators = 1;  
DROP FUNCTION IF EXISTS rand_string;  
CREATE FUNCTION rand_string(n INT)  
RETURNS VARCHAR(255)  
BEGIN  
    DECLARE chars_str varchar(100) DEFAULT 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';  
    DECLARE return_str varchar(255) DEFAULT '';  
    DECLARE i INT DEFAULT 0;  
    WHILE i < n DO  
        SET return_str = concat(return_str,substring(chars_str , FLOOR(1 + RAND()*62 ),1));  
        SET i = i +1;  
    END WHILE;  
    RETURN return_str;  
END ;

select rand_string(32);

set global log_bin_trust_function_creators = 1;  
DROP FUNCTION IF EXISTS imeiToUerId;
create function imeiToUerId(myiImei varchar(30))
returns integer
begin
DECLARE result integer DEFAULT 0;
select user_id into result from user_users where imei=myiImei LIMIT 1;
return result;
end;

功能:截取指定字符串  从  某子字符串 开始(包括子字符串)到指定字符串。
比如:CALL sp_str('小鸡跳棋_1.0.0_128:100;杨家将战斗_1.0.2_129:3267','小鸡跳棋',';',@result);(返回结果为:小鸡跳棋_1.0.0_128:100)
 

复制代码 代码示例:

set global log_bin_trust_function_creators = 1; 
DROP FUNCTION IF EXISTS subValue;
create function subValue(p_str VARCHAR(10000), p_begin_str VARCHAR(50), p_end_str VARCHAR(50))
returns VARCHAR(255)
begin
DECLARE p_result varchar(255) DEFAULT null;

DECLARE m_len INT DEFAULT 0;
DECLARE m_index INT DEFAULT 0;
select locate(p_begin_str,p_str)+char_length(p_begin_str) into m_index;
select locate(p_end_str,p_str,m_index) into m_len;
if(m_len=0) then
select SUBSTRING(p_str,m_index,char_length(p_str)) INTO p_result;
end if;

if(m_len>0) then
select SUBSTRING(p_str,m_index,m_len-m_index) INTO p_result;
end if;

select CONCAT(p_begin_str,p_result) into p_result;

return p_result;
end;

您可能感兴趣的文章:
mysql functions实例:loop循环 concat函数返回长串星号
mysql函数中使用repeat循环的例子
mysql functions实例:在自定义函数中应用字符串函数
mysql自定义函数的简单例子
mysql的call用法 嵌套函数调用的例子
mysql序列号生成器 mysql自定义函数生成序列号的例子
mysql case实例:带条件检测的case语句
mysql自定义函数与动态查询
php特殊字符转义详解
php中func_num_args与func_get_args函数的例子

[关闭]
~ ~