MySQL随机字符串生成

本文介绍了一个用于生成指定长度和类型的随机字符串的MySQL函数,包括参数解释、使用示例及实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. drop function if exists rand_string;     
  2. create function rand_string(str_length tinyint unsigned, str_type tinyint unsigned) returns varchar(255)   
  3. begin  
  4.     -- Function   : rand_string   
  5.     -- Author     : reymondtu#opencfg.com   
  6.     -- Date       : 2011/03/27   
  7.     -- Params     : str_length int unsigned    
  8.     --                  The random string length of random string   
  9.     --              str_type   int unsigned   
  10.     --                  The random string type   
  11.     --                      1.0-9   
  12.     --                      2.a-z   
  13.     --                      3.A-Z   
  14.     --                      4.a-zA-Z   
  15.     --                      5.0-9a-zA-Z   
  16.     --   
  17.     -- Example    :   
  18.     --   
  19.     -- mysql> select rand_string(32,5) from dual;   
  20.     -- +----------------------------------+   
  21.     -- | rand_string(32,5)                |   
  22.     -- +----------------------------------+   
  23.     -- | HbPBz4DWSAiJNLt4SgExHVwQI34bI6mt |   
  24.     -- +----------------------------------+   
  25.     -- 1 row in set   
  26.   
  27.     declare counter int unsigned default 0;   
  28.     declare const_chars varchar(64) default '0123456789';   
  29.     declare result varchar(255) default '';   
  30.     
  31.     if str_type = 1 then  
  32.         set const_chars = '0123456789';   
  33.     elseif str_type = 2 then  
  34.         set const_chars = 'abcdefghijklmnopqrstuvwxyz';   
  35.     elseif str_type = 3 then  
  36.         set const_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';   
  37.     elseif str_type = 4 then  
  38.         set const_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';   
  39.     elseif str_type = 5 then  
  40.         set const_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';   
  41.     else  
  42.         set const_chars = '0123456789';   
  43.     end if;   
  44.     
  45.     while counter < str_length do     
  46.         set result = concat(result,substr(const_chars,ceil(rand()*(length(const_chars)-1)),1));   
  47.     set counter = counter + 1;   
  48.     end while;   
  49.   
  50.     return result;   
  51. end  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值