Posted at

安全に使える乱数を生成する関数


MySQLで簡単に乱数を生成する関数。


DELIMITER $$
CREATE FUNCTION randomString(len INT)
RETURNS tinytext
BEGIN
declare r tinytext;
declare s tinytext default '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
declare n int;
set r='';
while length(r) < len do
set n=rand() * 61;
set r=concat(r,substr(s,n,1));
end while;
RETURN r;
END$$
DELIMITER ;


mysql> select randomString(10);

+------------------+
| randomString(10) |
+------------------+
| BL446jgqlr |
+------------------+
1 row in set (0.01 sec)

mysql> select randomString(4);
+-----------------+
| randomString(4) |
+-----------------+
| cEHA |
+-----------------+
1 row in set (0.00 sec)

mysql>