SQL获得固定长度的随机字符串

--获得固定长度的随机字符串
CREATE DEFINER=`root`@`localhost` FUNCTION `rand_string`(n INT) RETURNS varchar(255) CHARSET latin1
BEGIN
    DECLARE chars_str varchar(100) DEFAULT 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    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()*LENGTH(chars_str) ),1));
        SET i = i +1;
    END WHILE;
    RETURN return_str;

END;





这是mysql版,其他如Oracle SQLServ二,逻辑相同,只是语法稍作改动即可,配合存储过程,定义好字符库,可用来作为唯一随机码来用,可用于

类似创捷随机激活码来用


一个创建激活码的mysql 存储过程例子


--创建激活码
--category 创建激活码类型,创建数量
CREATE PROCEDURE create_activation_code(in category INTEGER,in count INTEGER)
BEGIN
DECLARE i int DEFAULT 0;
DECLARE code_index VARCHAR(20) default null;
DECLARE newCode VARCHAR(20);
DECLARE code_exists int DEFAULT 1 ;
DECLARE randomChar varchar(6);
DECLARE properties varchar(20);

--定义随机码长度
DECLARE code_length int DEFAULT 6;

if category = 1 then
set code_index = 'BYP';
set properties = '3001,1;';
elseif category = 2 then
set code_index = 'HJP';
set properties = '3002,1;';
elseif category = 3 then
set code_index = 'HGP';
set properties = '3003,1;';
end if;

while i<count do



while code_exists >= 1 do

set randomChar = rand_string(code_length);

set newCode = CONCAT(code_index,randomChar);
select count(1) into code_exists from Activation where activationCode = newCode;

end while;


insert Activation values(default,newCode,category,DEFAULT,DEFAULT,properties,default);
set i = i+1;
set code_exists = 1;
set randomChar = null;
end while;

END


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值