RSS
热门关键字:  linux  Java  服务器  安全  互联网
当前位置 :| linux库>Oracle>开发技术>

讲解Oracle里抽取随机数的多种方法

来源:linux库 作者:linuxku.com.cn 时间:2007-07-15 Tag: 点击:

在你的工作中是否会为了某个活动要随机取出一些符合条件的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;。

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;

5. tmp_1和tmp_2相关联取得符合条件的200用户

select t1.mobileno,t1.email from tmp_1 t1,tmp_2 t2 where t1.id=t2.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。


最新评论共有 0 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名?
注册