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
原文:http://www.cnblogs.com/Peyton-for-2012/p/4901700.html