您好,欢迎访问一九零五行业门户网

MySQL 随机生成各种类型的随机函数_MySQL

drop function if exists rand_string;
delimiter //
create function rand_string(l_num tinyint unsigned,l_type tinyint unsigned)
returns varchar(127)
begin
 -- function : rand_string
 -- author   : dbachina#dbachina.com
 -- date     : 2010/5/30
 -- l_num : the length of random string
 -- l_type: the string type
 --         1.0-9
 --         2.a-z
 --         3.a-z
 --         4.a-za-z
 --         5.0-9a-za-z
 -- :
  -- mysql> select rand_string(12,5) random_string;
  -- +---------------+
  -- | random_string |
  -- +---------------+
  -- | 3kzgjcujuplw  |
  -- +---------------+
  -- 1 row in set (0.00 sec)
 declare i int unsigned default 0;
 declare v_chars varchar(64) default '0123456789';
  declare result varchar ( 255) default '';
  if l_type = 1 then
    set v_chars = '0123456789';
  elseif l_type = 2 then
    set v_chars = 'abcdefghijklmnopqrstuvwxyz';
  elseif l_type = 3 then
    set v_chars = 'abcdefghijklmnopqrstuvwxyz';
  elseif l_type = 4 then
    set v_chars = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz';
  elseif l_type = 5 then
    set v_chars = '0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz';
  else
    set v_chars = '0123456789';
  end if;
  while i       set result = concat( result,substr(v_chars,ceil(rand()*(length(v_chars)-1)),1) );
    set i = i + 1;
  end while;
  return result;
end;
//
delimiter ;
其它类似信息

推荐信息