收藏本页 | 网站地图 | 投稿指南
 
 
当前位置:首页 >> 学院首页 >> 数据库 >> Oracle >>

ORACLE里取随机数的方法

放大字体  缩小字体  At: 2006-04-25 16:14  By: master8 转载 来源: 互联网


在你的工作中是否会为了某个活动要随机取出一些符合条件的EMAIL或者手机号码用户,来颁发获奖通知或其它消息?



如果是的话,可以用oracle里生成随机数的PL/SQL, 目录文件名在:/ORACLE_HOME/rdbms/admin/dbmsrand.sql。

用之前先要在sys用户下编译:



SQL>@/ORACLE_HOME/rdbms/admin/dbmsrand.sql



它实际是在sys用户下生成一个dbms_random程序包,同时生成公有同义词,并授权给所有数据库用户有执行的权限。



使用dbms_random程序包, 取出随机数据的方法:

1. 先创建一个唯一增长的序列号tmp_id



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



2. 然后创建一个临时表tmp_1,把符合本次活动条件的记录全部取出来。



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



找到最大的id号:



select max(id) from tmp_1;



假设为5000



3. 设定一个生成随机数的种子

execute dbms_random.seed(12345678);

或者

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

4. 调用随机数生成函数dbms_random.value生成临时表tmp_2



假设随机取200个



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间的随机数,会有小数,

trunc函数对随机数字取整,才能和临时表的整数ID字段相对应。



注意:如果tmp_1记录比较多(10万条以上),也可以找一个约大于两百行的表(假如是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相关联取得符合条件的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. 用完后,删除临时表tmp_1、tmp_2和序列号tmp_id。







         









 
Google
论坛精华  
 
 
  ©2005-2008 站长吧 Master8.NET All Rights Reserved 陕ICP备05010609号