1. 程式人生 > >mysql生成自定長度的隨機字串

mysql生成自定長度的隨機字串

...

DROP FUNCTION IF EXISTS random_str;
DELIMITER $$
CREATE FUNCTION random_str(n INT) RETURNS VARCHAR(255) 
BEGIN        
  DECLARE chars_str VARCHAR(100) 
  DEFAULT "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  DECLARE return_str VARCHAR(255) DEFAULT "";        
  DECLARE i INT DEFAULT 0;
  WHILE i < n DO        
      SET return_str=CONCAT(return_str,SUBSTRING(chars_str,FLOOR(1+RAND()*52),1));
      SET i= i+1;        
  END WHILE;        
  RETURN return_str;    
END $$
DELIMITER ;

...

例如,生成32位字串

SELECT random_str(32);