Skip to content

Instantly share code, notes, and snippets.

@imzhi
Last active March 14, 2016 03:07
Show Gist options
  • Select an option

  • Save imzhi/956472c3d7a2dd86a951 to your computer and use it in GitHub Desktop.

Select an option

Save imzhi/956472c3d7a2dd86a951 to your computer and use it in GitHub Desktop.
生成随机字符串(SQL函数)(http://www.jb51.net/article/61362.htm)
DROP FUNCTION `test`.`rand_str`;
SET GLOBAL log_bin_trust_function_creators=TRUE;
DELIMITER $$
CREATE
/*[DEFINER = { user | CURRENT_USER }]*/
FUNCTION `test`.`rand_str`(n INT UNSIGNED)
RETURNS VARCHAR(2000)
/*LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'*/
BEGIN
DECLARE char_str VARCHAR(100) DEFAULT 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
DECLARE return_str VARCHAR(2000) DEFAULT '';
DECLARE i INT DEFAULT 0;
WHILE i < n DO
SET return_str = CONCAT(return_str,SUBSTRING(char_str , FLOOR(1 + RAND()*62 ),1));
SET i = i +1;
END WHILE;
RETURN return_str;
END$$
DELIMITER ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment