(ORACLE8)DBMS_RANDOM PACKAGE를 이용하여 RANDOM NUMBER를 생성하는 방법

제품 : ORACLE SERVER
작성날짜 : 1999-03-04
(Oracle8)dbms_random package 를 이용하여 random number 를 생성하는 방법
=====================================================================
Oracle8 에서는 random number 를 생성하는 dbms_random package 를 제공한다.
이를 이용하여 random number 를 생성하는 방법을 알아본다.
1. sys user 로 접속하여 (또는 svrmgrl 에 connect internal) 다음의
script를 수행한다. script의 위치는 $ORACLE_HOME/rdbms/admin 이다.
dbmsoctk.sql, prvtoctk.plb, dbmsrand.sql
경우에 따라서는 utlraw.sql, prvtrawb.plb 를 먼저 수행해야 할 수도 있다.
2. random number generator 를 다음과 같이 초기화한다. randomness 를 보장
받기 위하여 seed 는 적어도 5 digits 이상으로 해야만 한다.
Example :
SQL> exec dbms_random.initialize (12345);
PL/SQL procedure successfully completed.
3. random number 를 생성한다.
Example 1 :
SQL> set serveroutput on
SQL> declare
2 random_number binary_integer;
3 begin
4 random_number := dbms_random.random;
5 dbms_output.put_line(to_char(random_number));
6 end;
7 /
2116177396
PL/SQL procedure successfully completed.
Example 2 :
DECLARE
i BINARY_INTEGER;
BEGIN
dbms_random.initialize(19254);
i := dbms_random.random;
INSERT INTO some_table VALUES(i);
dbms_random.terminate;
END;
4. memory 를 release 하기 위하여 random number generator 를 종료한다.
Example:
SQL> exec dbms_random.terminate;
PL/SQL procedure successfully completed.
5. random number generator 를 초기화한 이후에 seed 를 변경한다.
Example:
SQL> exec dbms_random.seed (12346);
PL/SQL procedure successfully completed.
6. 참고사항
a. dbms_random.terminate 을 이용하여 정상적으로 random number
generator 를 종료한 이후에 다시 dbms_random.random 를 수행하면
error 는 발생하지 않으나 값은 return 되지 않는다.
b. random 함수를 바로 SQL 문장에 사용할 수 없다.
Example:
SQL> exec dbms_random.initialize (12345);
PL/SQL procedure successfully completed.
SQL> insert into x values(dbms_random.random);
insert into x values(dbms_random.random)
ERROR at line 1:
ORA-06571: Function RANDOM does not guarantee
not to update the database.

Similar Messages

  • Dbms_random package

    hallo,
    i would like to know how DBMS_RANDOM package can be implemented.
    can you please explain with example.
    is there any other means of performimg random sampling?
    thank you
    regards,
    rao

    Hi
    Desc DBMS_RANDOM;
    PROCEDURE INITIALIZE
    Názov argumentu Typ In/Out predvolene?
    VAL BINARY_INTEGER IN
    FUNCTION NORMAL RETURNS NUMBER
    FUNCTION RANDOM RETURNS BINARY_INTEGER
    PROCEDURE SEED
    Názov argumentu Typ In/Out predvolene?
    VAL BINARY_INTEGER IN
    PROCEDURE SEED
    Názov argumentu Typ In/Out predvolene?
    VAL VARCHAR2 IN
    FUNCTION STRING RETURNS VARCHAR2
    Názov argumentu Typ In/Out predvolene?
    OPT CHAR IN
    LEN NUMBER IN
    PROCEDURE TERMINATE
    FUNCTION VALUE RETURNS NUMBER
    FUNCTION VALUE RETURNS NUMBER
    Názov argumentu Typ In/Out predvolene?
    LOW NUMBER IN
    HIGH NUMBER IN
    Example in SQL+:
    Exec DBMS_RANDOM.INITIALIZE(100);
    SELECT DBMS_RANDOM.Normal
    , DBMS_RANDOM.RANDOM
    , DBMS_RANDOM.VALUE()
    , DBMS_RANDOM.VALUE(10,100)
    FROM DUAL;
    milos

  • Error from dbms_random package

    I have tried unsuccessfully to get the dbms_random package installed. This is my latest error message. Can anyone help me out?
    call dbms_random.initialize(12345)
    ERROR at line 1:
    ORA-04068: existing state of packages has been discarded
    ORA-04063: package body "SYS.DBMS_CRYPTO_TOOLKIT" has errors
    ORA-06508: PL/SQL: could not find program unit being called
    ORA-06512: at "SYS.DBMS_RANDOM", line 19
    ORA-06512: at line 1
    null

    If you are running Oracle8 Release 8.0.3, DBMS_RANDOM may not have been installed in your database. In this case, you need to execute the following scripts in the specified order from within your SYS account: dbmsoctk.sql, prvtoctk.plb, and finally dbmsrand.sql (it contains both the package specification and body for DBMS_RANDOM).
    Good Luck

  • How can I create a random number and letter in a text field...

    Hi All,
    I am using application express. I want to get a random number and letter for a text field but not sure how to do this. Say I have a licence form and I want to get the licence number automatically when user wants to create a new licence and it needs to be unique. The format I am looking for is - HQ2631 something like this.
    I am thinking I have to create a trigger but not sure how to go about this....
    advanced thanks,
    Tajuddin

    Something to play with:
    Your method can generate 26 * 26 * 10000 different licence_ids
    Generating one million ids takes 20 seconds but produces between 70000 and 80000 duplicates and is rapidly getting worse (if that is something over 7%, doubling the ids generated that grows to something under 30%)
    Just see if you can live with that.
    select sum(collisions) all_duplicates,count(*) distinct_duplicates,max(collisions) max_multiple
      from (select licence_id,count(*) - 1 collisions
              from (select DBMS_RANDOM.STRING('',2) || trunc(DBMS_RANDOM.VALUE(1000,9999)) licence_id
                      from dual
                     connect by level <= :to_generate
             group by licence_id
             having count(*) > 1
           )Regards
    Etbin

  • Random number generation that sticks

    Hello,
    I would appreciate any help with the appropriate JavaScript to generate a random 8 digit number XXXX-XXXX on a form when the user starts to enter data. This number would need to be permanent so that it can be used as a tracking identifier later.
    Thanks for looking.
    Dawson

    If you're using Oracle8i, you can use the new SAMPLE clause in the FROM clause of the SELECT statement to query a random sample from a single table. Otherwise, just write a simple random number generator in PL/SQL (see any good algorithm book under the topic "Psuedorandom number generator"). You need to understand a bit about statistics, if being "truly" random is important, to use these tools.

  • Random number generation with format 18XX88YYYYY

    I have been tryig to generate random numbers having
    format 18xx88yyyyy
    here
    18 followed by two random number then 88 followed by five random number. here 18 and 88 are fixed at location one,two,five and sixth position.
    but I am unable to get the logic .
    So please help
    Thanx
    Achyot

    After changing the column from number to varchar2 I am getting my correct result...
    create or replace function generateRandom return varchar2 is
    random varchar2(11);
    begin
    SELECT '18'|| lpad(ROUND (DBMS_RANDOM.VALUE (0, 100)),2,'0')|| '88'|| lpad(ROUND (DBMS_RANDOM.VALUE (0,
    100000)),5,'0')
    into random FROM DUAL;
    return random;
    end;
    create or replace procedure insertRandom is
    getNum varchar2(11);
    x number(3);
    cnt number;
    cursor checkpk is
    select random_no n from rand_no;
    begin
    cnt:=0;
    while (cnt<3054) loop
    x:=0;
    getNum:=generateRandom;
    for pkcheck in checkpk loop
    if getNum=pkcheck.n then
    x:=x+1;
    end if;
    end loop;
    if x=0 then
    insert into rand_no values(getNum);
    end if;
    select count(*) into cnt from rand_no;
    end loop;
    commit;
    end insertRandom;
    output:
    RANDOM_NO
    18388817929
    18658842315
    18028870847
    18898822037
    18678818255
    18248878003
    18558852407
    18878870907
    18998892135
    18538876212
    18908820740
    Thanx you everyone...

  • Random Number in the Transformation File

    Hi All,
    I need to send a random number while mapping from one xsd to other in the xsl file . The random number should be alpha numeric with 5 chartacters. I tried using generate-guid() but it generates 32 characters. How do u i shrink this to 5 characters and still get a random value?
    Thanks
    MJ

    Just to add,
    the above mentioned function does not generate integers. For that u need to truncate the output of random to integer as below
    SELECT TRUNC(dbms_random.value(10000, 99999)) FROM dual;
    Edited by: Marius J on Sep 15, 2009 1:33 AM

  • Random number in range generator plz help!

    hey hope someone can help me out, im sure its an easy one:
    var tstArray:Array = new Array(1,2,3);
    for (var a:uint=0; a<tstArray.length; a++)
    var x:Number = Math.floor((Math.random()*tstArray[a]));
    trace(x);
    tstArray.splice(a,1);
    i have this code but it doesnt do exectply what i want it to do. Im trying to generate a signle random number per click between 1 and 3 and when all numbers have been used up, remove this click listener.
    if u can help it'll be much appriciated
    thx pavel

    use:
    var fp1:farm_part1=new farm_part1();
    and any time you want to randomize an array use:
    var tstArray:Array = fp1.randomizeF([1,2,3]);
    package
    */import flash.utils.Timer;
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.*;
    import flash.media.Sound;
    import flash.events.TimerEvent;
    import flash.media.SoundChannel;
    import flash.media.SoundTransform;*/
    public class farm_Part1
    public function randomizeF(a:Array):Array
    {a.shuffle();
    return a;
    ///////////////////////////// change nothing below /////////////////////////////////////////
    function shuffle(a:Array)
    var p:int;
    var t:*;
    var ivar:int;
    for (ivar = a.length-1; ivar>=0; ivar--)
    p=Math.floor((ivar+1)*Math.random());
    t = a[ivar];
    a[ivar] = a[p];
    a[p] = t;
    }//randomAnimal
    }//class
    }//package

  • Random number issue

    I'm making a mobile game and I can't seem to generate a random number successfully
    Game.java:
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    public class Game extends MIDlet implements CommandListener {
    private Display theDisplay;
    private GameCanvas canvas;
    private Player p1;
    private Block[] Grid;
    static final Command exitCommand = new Command("Exit", Command.STOP, 1);
    class Player {
      public int x, y;
      public int width=60, height=15;
      public Player(int curX, int curY) {
       x = curX;
       y = curY;
    public Game() {
      setupGrid(5, 8, 5);
      p1 = new Player(90, 250);
      theDisplay = Display.getDisplay(this);
    private void setupGrid(int rows, int cols, int cellspacing) {
      Grid = new Block[200];
      int ind = 0;
      int posX = 10;
      int posY = 20;
      int colPosY;
      int colPosX;
      colPosY = posY;
      colPosX = posX;
      for(int x = 0; x < rows; x++) {
       Grid[ind] = new Block(posX, posY);
       colPosY = posY;
       for(int y = 0; y < cols; y++) {
        ind++;
        colPosX += 20+cellspacing;
        colPosY = posY;
        Grid[ind] = new Block(colPosX, colPosY);
       colPosX = posX;
       posY += 15+cellspacing;
       ind++;
    class Block {
       public int x, y;
       public int Health;
       public int r = 0, g = 0, b = 0;
       public Block(int curX, int curY) {
       x = curX;
       y = curY;
       double rand = Math.random()*5;
       if(rand > 0 && rand < 2) {
        g = 255;
        r = 0;
        b = 0;
       if(rand > 2 && rand < 4) {
        r = 255;
        g = 0;
        b = 0;
       if(rand > 3 && rand < 5) {
        b = 255;
        g = 0;
        r = 0;
    class GameCanvas extends Canvas {
      private int width;
      private int height;
      GameCanvas() {
       width = getWidth();
       height = getHeight();
      public void paint(Graphics g) {
       g.setColor(0, 0, 0);
       g.fillRect(0, 0, width, height);
       g.setColor(100, 100, 100);
       g.fillRect(p1.x, p1.y, p1.width, p1.height);
       for(int x = 0; x < Grid.length; x++) {
        if(Grid[x] != null) {
         g.setColor(Grid[x].r, Grid[x].g, Grid[x].b);
         g.fillRect(Grid[x].x, Grid[x].y, 20, 10);
      public void keyPressed(int keyCode) {
       int key = getGameAction(keyCode);
       if(key == LEFT && p1.x > 0) {
        p1.x-=4;
       else if(key == RIGHT && p1.x < canvas.width-p1.width) {
        p1.x+=4;
       repaint();
    protected void startApp() throws MIDletStateChangeException {
      canvas = new GameCanvas();
      canvas.addCommand(exitCommand);
      canvas.setCommandListener(this);
      theDisplay.setCurrent(canvas);
    public void pauseApp() { }
    public void destroyApp(boolean unconditional) { }
    public void commandAction(Command c, Displayable d) {
      if(c == exitCommand) {
       destroyApp(false);
       notifyDestroyed();
    }Game.java:58: cannot find symbol
    symbol : method random()
    location: class java.lang.Math
    double rand = Math.random()*5;
    ^
    1 error
    Line 58:
    double rand = Math.random()*5;

    b1nary wrote:
    Unfortunately, no - it won't work. Prior to posting this thread I researched different ways to generate random numbers but, apparently, the WTK only allows certain packages to be recognized.You can always write your own generator. For portability I use
    * Uniform random number generator.
    * <p>
    * Based on
    * <blockquote>
    * <pre>
    * Efficient and Portable Combined Random Number Generators
    * <a href="http://www.iro.umontreal.ca/~lecuyer">Pierre L'Ecuyer</a>
    * Communications of the ACM
    * June 1988 Volume 31 Number 6
    * </pre>
    * </blockquote>
    * @author Sabre
    public class Ecuyer
         * Constructs the generator based on two starting seeds.
         * <p>
         * Two generators using the same pair of seeds will produce
         * exactly the same sequence of pseudo random numbers.
         * @param seed1 the starting seed.
         * @param seed2 the second starting seed.
        public Ecuyer(int seed1, int seed2)
            s1 = (seed1 > 0) ? seed1 : 1;
            s2 = (seed2 > 0) ? seed2 : 1;
         * Constructs the generator based on a starting seed.
         * <p>
         * Two generators using the same seeds will produce
         * exactly the same sequence of pseudo random numbers.
         * @param seed the starting seed.
        public Ecuyer(long seed)
            this((int) ((seed >> 32) & 0x7fffffff), (int) (seed & 0x7fffffff));
         * Constructs a generator using the current time as seed.
        public Ecuyer()
            this(System.currentTimeMillis());
         * Returns the next random number
         * @return the next random number
        public double nextValue()
                // m = 2147483563, a = 40014
                int k = s1 / q1;
                s1 = a1 * (s1 - k * q1) - k * r1;
                if (s1 < 0)
                    s1 += m1;
                // m = 2147483399, a = 40692
                int k = s2 / q2;
                s2 = a2 * (s2 - k * q2) - k * r2;
                if (s2 < 0)
                    s2 += m2;
            int z = s1 - s2;
            if (z < 0)
                z += m1;
            return z * 4.656613e-10;
        static final int m1 = 2147483563;
        static final int a1 = 40014;
        static final int q1 = 53668;
        static final int r1 = 12211;
        static final int m2 = 2147483399;
        static final int a2 = 40692;
        static final int q2 = 52774;
        static final int r2 = 3791;
        private int s1;
        private int s2;
    }Make sure you test it thoroughly before committing to it.

  • Generate random number and letter in a text field ...

    Hi All,
    I having a bit trouble when trying to generate random number and letter in application express in a text field. Say I have a licence form and when user wants to create a licence, it will provide a random licence number in the licence number field but it has to be unique. the number should be something like HQ2345. I was trying to set the following sql in default value for that text field but it is not working -
    select DBMS_RANDOM.STRING('',2) || trunc(DBMS_RANDOM.VALUE(1000,9999))
    from dual;
    any suggesion !!!!
    thanks

    Put this as default value for your text-item
    DBMS_RANDOM.STRING('',2) || trunc(DBMS_RANDOM.VALUE(1000,9999))
    with type PL/SQL Expression. It have tested it and it works fine.
    DickDral

  • RANDOM NUMBER를 GENERATE하는 PL/SQL 문.

    제품 : ORACLE SERVER
    작성날짜 : 2002-04-17
    RANDOM NUMBER 를 생성하는 PACKAGE
    1. 다음은 random number를 생성하는 script 이다.
    create or replace package random
    is
    pragma restrict_references(random, WNDS);
    function rand(i in number) return number;
    pragma restrict_references(rand, WNDS, WNPS);
    procedure seed_it;
    end random;
    create or replace package body random
    is
    type numTable is table of number index by binary_integer;
    random_numbers numTable;
    multiplier constant number := 22695477;
    increment constant number := 1;
    "2^32" constant number := 2 ** 32;
    "2^16" constant number := 2 ** 16;
    "0x7fff" constant number := 32767;
    Seed number := 1;
    function rand( i in number ) return number
    is
    begin
    return random_numbers( mod(i,500)+1 );
    end rand;
    procedure seed_it
    is
    begin
    for i in 1 .. 500 loop
    seed := mod( multiplier * seed + increment, "2^32" );
    random_numbers(i) := bitand( seed/"2^16", "0x7fff" );
    end loop;
    end seed_it;
    begin
    select userenv( 'SESSIONID' )
    into Seed
    from dual;
    end random;
    2. 이를 실행시는
    SQL> execute random.seed_it
    PL/SQL procedure successfully completed.
    SQL> variable aaa number
    SQL> execute :aaa:=random.rand(1)
    PL/SQL procedure successfully completed.
    SQL> print aaa

  • Generate Random Number By sequence

    How to generate random 4 digit random number using sequence or any other method. Please suggest

    4 digit random numbers can be obtained by:
    SQL> SELECT TRUNC(DBMS_RANDOM.VALUE(1000,9999)) FROM DUAL;
    TRUNC(DBMS_RANDOM.VALUE(1000,9999))
                                   4002
    SQL> /
    TRUNC(DBMS_RANDOM.VALUE(1000,9999))
                                   4748
    SQL> /
    TRUNC(DBMS_RANDOM.VALUE(1000,9999))
                                   8328
    SQL> /
    TRUNC(DBMS_RANDOM.VALUE(1000,9999))
                                   3667
    SQL> /
    TRUNC(DBMS_RANDOM.VALUE(1000,9999))
                                   7464
    SQL> /
    TRUNC(DBMS_RANDOM.VALUE(1000,9999))
                                   4893
    SQL> /
    TRUNC(DBMS_RANDOM.VALUE(1000,9999))
                                   4961In mine case there is no repetition using Oracle 11.2.0.1 on Windows XP.
    Regards
    Girish Sharma

  • Generating random number

    Hi
    I am making an assignment in which I have a discrete random number tellig the probaily of the locations of a person in a city.There are around 50 locations and probablity for each is calculated.Now in my program I have to randomly choose 1 location.Can anyone tell me how to do it.I know there is Random Class in java.util package but thats for continuous random numbers and also I dont have much knowledge about random number generators.
    thanks in advance

    P.S. The doube data type isavailable only in JDK versions 9.72 and above.
    Ok very funny, we all know he meant "doobie"Well, I, for one, thought he meant "doubt"...asin, "I have a doubt in ...". ;)
    Oh No! They got you too? :(Quick! Burn her before it spreads even further!No, no! I didn't even think about it until after the
    "doobie" was posted as the correct word instead of
    "doube". But, given where some people here think
    this use of "doubt" originates [countrywise], maybe
    other influences caused me to think of it...
    I would never say "doubt" in that context
    myself.We have to use science to make sure we are doing the right thing! Does anyone have a duck and a big wooden scale?
    � {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • 3 digit random number

    Hi All,
    While running my application,I want to generate 3digit random number.
    Is there any pre defined function.If not please suggest me some idea to get the same
    Thanks in advance

    SQL> EXEC DBMS_RANDOM.VALUE(100,999)
    BEGIN DBMS_RANDOM.VALUE(100,999); END;
    FOUT in regel 1:
    .ORA-06550: line 1, column 7:
    PLS-00306: wrong number or types of arguments in call to 'VALUE'
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignored
    SQL> select dbms_random.value(100,999) from dual;
                DBMS_RANDOM.VALUE(100,999)
    338,5994241488838095483116070509848701
    1 rij is geselecteerd.
    SQL> select trunc(dbms_random.value(100,1000)) from dual;
        TRUNC(DBMS_RANDOM.VALUE(100,1000))
                                       918
    1 rij is geselecteerd.Regards,
    Rob.

  • Generate Random number-Dynamic.

    Guys,
    I'm looking for a pl\sql block to generate a 10 digit random number.
    Could someone help me out?
    Also, is there anyway to make it dynamic?..ie.If i pass 4 to the procedure\function, it should generate a 4 digit number..Thoughts please?
    Regards,
    Bhagat

    Please read about [url http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_random.htm#sthref4646]DBMS_RANDOM in the manual.

Maybe you are looking for

  • Finding out what IP is connected to my network

    I set up a wireless device network from my mac and connected another wireless device to it. Is there a way, through my OSX that I can find out what IP the device is using on my mac's custom network?

  • Why will twitpic pictures not load in firefox but will in internet explorer?

    Why suddenly have twitpic pictures stopped loading in Firefox. They load in internet Explorer but just stopped loading on the twitpic site in Firefox??

  • A new Account

    Hello, I have a problem with Itunes 7,02. I created a Apple ID and would creat me a Account for buying music in the itunesstore. I have write full the option of account but if i will used "click and buy" as terms of payment then the creat button go n

  • Mail tagged as "not junk" is hidden and produces console error

    Mail has developed a strange quirk since the latest OS update. Can anyone help me fix it? Whenever I un-mark email that was automatically marked as junk, the messages become hidden in the inbox. By "hidden" I mean that the next time I run mail, there

  • How to import JSTL 1.2 to adf 11g?

    Hi, Any one happen to have a working example on how to use JSTL in jsff ? Thank you