当前位置: 移动技术网 > IT编程>数据库>Oracle > Oracle 随机数

Oracle 随机数

2017年12月12日  | 移动技术网IT编程  | 我要评论

成龙歌曲,郑阳警官学院,刘天礼吉他教学

利用oracle的dbms_random包结合rownum来实现,示例如下,随机取499户:
select * from
( select * from busi.t_ar_userinfo order by dbms_random.value)
where rownum < 500;

有关dbms_random的参考文献,链接为:http://www.psoug.org/reference/dbms_random.html

deprecated. use the methods in the dbms_crypto built-in package,这个包已经不建议使用了

附,dbms_random几个参数的介绍:
function value return number,返回一个[0,1)之间的随机数,精度为38位(gets a random number, greater than or equal to 0 and less than 1, with decimal 38 digits)
function value(low in numvber,high in number) return number,返回一个[low,high)之间的随机数
function normal return number,return random numbers in a standard normal distribution,返回服从正态分布的一组数,标准偏差为1,期望值为0,返回值中68%介于+1 和 -1 之间,95%介于 +2 和 -2 之间,99%介于+3 和 -3之间。
function random return binary_integer, (generate random numeric values),
function string(opt char,length number) return varchar2(the maximum is 60),返回一个指定长度的字符串( create random strings),opt seed values:
'a','a'&n

问:我工作中的问题:主管让我为了某个活动要随机取出一些符合条件的email或者手机号码用户,来颁发获奖通知或其它消息,我们公司用的oracle 9i 请问这个如何实现?  
答:可以用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。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网