Oracle dbms_random包的用法

來源:互聯網
上載者:User

1.dbms_random.value方法

dbms_random是一個可以產生隨機數值或者字串的程式包。這個包有initialize()、seed()、terminate()、value()、normal()、random()、string()等幾個函數,但value()是最常用的,value()的用法一般有兩個種,第一
function value return number;
這種用法沒有參數,會返回一個具有38位精度的數值,範圍從0.0到1.0,但不包括1.0,如下樣本:
SQL> set serverout on
SQL> begin
   2    for i in 1..10 loop
   3      dbms_output.put_line(round(dbms_random.value*100));
   4    end loop;
   5  end;
   6  /
46
19
45
37
33
57
61
20
82
8
 
PL/SQL 過程已成功完成。
 
SQL> 
 
第二種value帶有兩個參數,第一個指下限,第二個指上限,將會產生下限到上限之間的數字,但不包含上限,“學無止境”兄說的就是第二種,如下:
SQL> begin
   2    for i in 1..10 loop
   3      dbms_output.put_line(trunc(dbms_random.value(1,101)));
   4    end loop;
   5  end;
   6  /
97
77
13
86
68
16
55
36
54
46
 
PL/SQL 過程已成功完成。

2. dbms_random.string 方法

某些使用者管理程式可能需要為使用者建立隨機的密碼。使用10G下的dbms_random.string 可以實現這樣的功能。

例如:
SQL> select dbms_random.string('P',8 ) from dual ;
 
DBMS_RANDOM.STRING('P',8)
--------------------------------------------------------------------------------
3q<M"yf[
 
第一個參數的含義:
■ 'u', 'U' - returning string in uppercase alpha characters
■ 'l', 'L' - returning string in lowercase alpha characters
■ 'a', 'A' - returning string in mixed case alpha characters
■ 'x', 'X' - returning string in uppercase alpha-numeric
characters
■ 'p', 'P' - returning string in any printable characters.
Otherwise the returning string is in uppercase alpha
characters.
P 表示 printable,即字串由任意可列印字元構成

而第二個參數表示返回的字串長度。
3. dbms_random.random 方法
    random返回的是BINARY_INTEGER類型值,產生一個任意大小的隨機數
  與dbms_random.value 的區別舉例:
   Order By dbms_random.value;
這條語句功能是實現記錄的隨機排序
另外:
dbms_random.value 和dbms_random.random 兩者之間有什麼區別?
1。Order By dbms_random.value ,為結果集的每一行計算一個隨機數,dbms_random.value 是結果集的一個列(雖然這個列並不在select list 中),然後根據該列排序,得到的順序自然就是隨機的啦。
2。看看desc資訊便知道vlue和random這兩個函數的區別了,value返回的是number類型,並且返回的值介於1和0之間,而random返回的是BINARY_INTEGER類型(以二進位形式儲存的數字,據說運算的效率高於number但我沒測試過,但取值範圍肯定小於number,具體限制得查資料了)
如果你要實現隨機排序,還是用value函數吧

4. dbms_random.normal方法

NORMAL函數返回服從常態分佈的一組數。此常態分佈標準差為1,期望值為0。這個函數返回的數值中有68%是介於-1與+1之間,95%介於-2與+2之間,99%介於-3與+3之間。

5. dbms_random.send方法 

用於產生一個隨機數種子,設定種子的目的是可以重複產生隨機數,用於調試。否則每次不同,難以調度。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.