LoginSignup
0

More than 5 years have passed since last update.

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

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>

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0