tags:

views:

94

answers:

3

In C# I can generate random number from a string like this:

public string CreateRandomNumber(string normal)
{
    string abnormal = (new Random(normal.GetHashCode())).Next().ToString();
    return abnormal;
}

But I want to do the same (kind of) operation inside the oracle database. So, how can I generate a random number from a string ?

+1  A: 

Take a look here:

http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:831827028200

where he uses a combination of sys_guid and to_number.

davek
thanks for your assistance.
Mr. Flint
+1  A: 

There is a package in Oracle called DBMS_RANDOM, but it only takes numbers as seed. To seed it with a string, you need some way to generate a numeric hash code for the string. Something along the lines of

FUNCTION simpleHash(st varchar2) RETURN NUMBER is
  n NUMBER;
  s NUMBER;
BEGIN
  n:=1;
  s:=0;
  FOR i IN 1..LENGTH(st) LOOP
     s:=s+n*ASCII(SUBSTR(st,i,1));
     n:=mod(n*75, 65537);
  END LOOP;
END;
/

should do the trick.

ammoQ
Thanks for your assistance. But i used dbms_random.seed() since it seems easier to me. And i did not forget to up vote you.
Mr. Flint
Sure. The doc I've found didn't show the dbms_random.seed(VARCHAR2) function, so I offered an alternative.
ammoQ
+3  A: 

The DBMS_RANDOM package provides a built-in random number generator.

Using the SEED Procedures, you can pass a VARCHAR2 as the seed, so you can skip the hash generation step.

SEED Procedures

This procedure resets the seed.

Syntax

DBMS_RANDOM.SEED (
   seed  IN  BINARY_INTEGER);

DBMS_RANDOM.SEED (
   seed  IN  VARCHAR2);
gimel
Hi, i need to get the same random number every time i call with the same string. But after using: dbms_random.seed('temp'), i get two different random numbers for two dbms_random.value calls.
Mr. Flint
Maybe a string hash is enough. GET_HASH_VALUE - http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_util.htm#sthref7794
gimel
The seed starts a particular *sequence* of "random" numbers. If you want the same value over and over, store it somewhere (e.g. in a variable), or re-seed every time.
Jeffrey Kemp