Oracle存储过程生成大量不重复的随机数

存放随机数的表结构:
create table COUPON_CODE
(
ID NUMBER(22),--主键
CODE VARCHAR2(10),--随机数
USED VARCHAR2(2)--是否使用标识
)

需求说明:生成1亿条随机数存放到code字段,字段id为主键,取值从1到1亿,要求code值为从1到1亿之间的随机数,且不能重复,code字段类型为字符,长度都固定为8位,不足的在左边补0.

实现思路:每次插入一条数据,ID值和CODE值相同,同时计数器加1,再从已经插入的数据中取出一个随机ID,查出这个ID对应的CODE值,将最新插入的记录的CODE值与随机取得的记录的CODE值互换。

测试结果:生成1W条随机数用时159s

存储过程代码:
create or replace procedure insert_random_couponCode(maxNum in number) is
currentId number(9);
randomId number(9);
randomCode varchar2(9);
currentCode varchar2(9);
querySql varchar2(2000);
updateSql varchar2(2000);
type c_mycur is ref cursor;
c_cur c_mycur;
begin
select max(id) into currentId from coupon_code;
if(currentId is null)then
insert into coupon_code(id,code)values(1,'00000001');
commit;
currentId:=1;
end if;
open c_cur for 'select t.id,t.code from coupon_code t';
loop
currentId:=currentId+1;
currentCode:=trim(to_char(currentId,'09999999'));
querySql:='select abs(mod(dbms_random.random,'||currentId||')) from dual';
execute immediate querySql into randomId;
if randomId=0 then
randomId:=1;
end if;
querySql:='select t.code from coupon_code t where t.id='||randomId;
execute immediate querySql into randomCode;
updateSql:='begin insert into coupon_code(id,code)values('||currentId||','''||randomCode||''')'||
';update coupon_code set code='''||currentCode||''' where id='||randomId||';end;';
execute immediate updateSql;
commit;
exit when currentId=maxNum;
end loop;
close c_cur;
dbms_output.put_line('finished !');
exception
when others then
rollback;
dbms_output.put_line('exception!!!');
end insert_random_couponCode;
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值