1. 程式人生 > >Oracle儲存過程生成大量不重複的隨機數

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;