Home > Database > Mysql Tutorial > body text

MySQL中随机生成固定长度字符串的方法

WBOY
Release: 2016-06-07 18:02:59
Original
1294 people have browsed it

在MySQL中有时需要随机生成数字或字符串,随机生产数字可直接使用rand()函数,但是要随机生成字符串就比较麻烦。

要随机生成字符串代码如下:

在MySQL中定义一个随机串的方法,然后再SQL语句中调用此方法。

随机串函数定义方法:
代码如下:
CREATE DEFINER=`root`@`localhost` FUNCTION `rand_string`(n INT) RETURNS varchar(255) CHARSET latin1
BEGIN
DECLARE chars_str varchar(100) DEFAULT 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
DECLARE return_str varchar(255) DEFAULT '';
DECLARE i INT DEFAULT 0;
WHILE i SET return_str = concat(return_str,substring(chars_str , FLOOR(1 + RAND()*62 ),1));
SET i = i +1;
END WHILE;
RETURN return_str;
END;

使用随机串函数方法示例:
UPDATE demotable SET demoname=rand_string(32) WHERE id>23
直接执行即可。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template