實(shí)例講解Oracle里抽取隨機(jī)數(shù)的多種方法

2010-08-28 10:51:35來源:西部e網(wǎng)作者:

  在你的工作中是否會(huì)為了某個(gè)活動(dòng)要隨機(jī)取出一些符合條件的EMAIL或者手機(jī)號碼用戶,來頒發(fā)獲獎(jiǎng)通知或其它消息?本文以實(shí)例的方式來講解如何抽取隨機(jī)數(shù)的多種方法。
  如果是的話,可以用oracle里生成隨機(jī)數(shù)的PL/SQL, 目錄文件名在:/ORACLE_HOME/rdbms/admin/dbmsrand.sql。

  用之前先要在sys用戶下編譯:SQL>@/ORACLE_HOME/rdbms/admin/dbmsrand.sql。

  它實(shí)際是在sys用戶下生成一個(gè)dbms_random程序包,同時(shí)生成公有同義詞,并授權(quán)給所有數(shù)據(jù)庫用戶有執(zhí)行的權(quán)限。

  使用dbms_random程序包, 取出隨機(jī)數(shù)據(jù)的方法:

  1. 先創(chuàng)建一個(gè)唯一增長的序列號tmp_id:

create sequence tmp_id increment by 1 start with 1 maxvalue 9999999 nocycle nocache;


  2. 然后創(chuàng)建一個(gè)臨時(shí)表tmp_1,把符合本次活動(dòng)條件的記錄全部取出來:

create table tmp_1 as select tmp_id.nextval as id, email,mobileno from 表名 where 條件;


  找到最大的id號:select max(id) from tmp_1;。

  3. 設(shè)定一個(gè)生成隨機(jī)數(shù)的種子:

execute dbms_random.seed(12345678); 或者 execute dbms_random.seed (TO_CHAR(SYSDATE,'MM-DD-YYYY HH24:MI:SS'));


  4. 調(diào)用隨機(jī)數(shù)生成函數(shù)dbms_random.value生成臨時(shí)表tmp_2(假設(shè)隨機(jī)取200個(gè)):

create table tmp_2 as select trunc (dbms_random.value(1,5000)) as id from tmp_1 where rownum<201;


  [ 說明:dbms_random.value(1,5000)是取1到5000間的隨機(jī)數(shù),會(huì)有小數(shù),

  trunc函數(shù)對隨機(jī)數(shù)字取整,才能和臨時(shí)表的整數(shù)ID字段相對應(yīng)。

  注意:如果tmp_1記錄比較多(10萬條以上),也可以找一個(gè)約大于兩百行的表(假如是tmp_3)來生成tmp_2

create table tmp_2 as select trunc(dbms_random.value(1,5000)) as id from tmp_3 where rownum<201; ]


  5. tmp_1和tmp_2相關(guān)聯(lián)取得符合條件的200用戶

select t1.mobileno,t1.email from tmp_1 t1,
tmp_2 t2 where t1.id=t2.id;


  [ 注意:如果tmp_1記錄比較多(10萬條以上),需要在id字段上建索引。]

  也可以輸出到文本文件:

set pagesize 300;
spool /tmp/200.txt;
select t1.mobileno,t1.email from tmp_1 t1,
tmp_2 t2 where t1.id=t2.id order by t1.mobileno;
spool off;


  6. 用完后,刪除臨時(shí)表tmp_1、tmp_2和序列號tmp_id。

關(guān)鍵詞:Oracle

贊助商鏈接: