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

【转】MySQL随机字符串生成

2015-10-22 17:27 651 查看
DROP FUNCTION IF EXISTS rand_string;

DELIMITER $$

CREATE FUNCTION rand_string(str_length TINYINT UNSIGNED, str_type TINYINT UNSIGNED) RETURNS VARCHAR(255)
BEGIN
-- Function   : rand_string
-- Author     : reymondtu#opencfg.com
-- Date       : 2011/03/27
-- Params     : str_length int unsigned
--                  The random string length of random string
--              str_type   int unsigned
--                  The random string type
--                      1.0-9
--                      2.a-z
--                      3.A-Z
--                      4.a-zA-Z
--                      5.0-9a-zA-Z
--
-- Example    :
--
-- mysql> select rand_string(32,5) from dual;
-- +----------------------------------+
-- | rand_string(32,5)                |
-- +----------------------------------+
-- | HbPBz4DWSAiJNLt4SgExHVwQI34bI6mt |
-- +----------------------------------+
-- 1 row in set

DECLARE counter INT UNSIGNED DEFAULT 0;
DECLARE const_chars VARCHAR(64) DEFAULT '0123456789';
DECLARE result VARCHAR(255) DEFAULT '';

IF str_type = 1 THEN
SET const_chars = '0123456789';
ELSEIF str_type = 2 THEN
SET const_chars = 'abcdefghijklmnopqrstuvwxyz';
ELSEIF str_type = 3 THEN
SET const_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
ELSEIF str_type = 4 THEN
SET const_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
ELSEIF str_type = 5 THEN
SET const_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
ELSE
SET const_chars = '0123456789';
END IF;

WHILE counter < str_length DO
SET result = CONCAT(result,SUBSTR(const_chars,CEIL(RAND()*(LENGTH(const_chars)-1)),1));
SET counter = counter + 1;
END WHILE;

RETURN result;
END  ;

$$
DELIMITER ;


转自:http://tuhaitao.iteye.com/blog/976936
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: