---
title: "Oracle存储过程生成大量不重复的随机数"
author: "gu6866"
date: "2011-12-25T03:26:39Z"
tags: []
categories: ["数据库"]
slug: "oracle"
draft: false
lastmod: "2012-08-24T14:21:44Z"
id: 1325122
url: "https://premier9527.iteye.com/blog/1325122"
---

存放随机数的表结构：
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;