I need a different random number for each row in my table. The following seemingly obvious code uses the same random value for each row.
SELECT table_name, RAND() magic_number
FROM information_schema.tables
I'd like to get an INT or a FLOAT out of this. The rest of the story is I'm going to use this random number to create a random date offset from a known date, e.g. 1-14 days offset from a start date.
This is for Microsoft SQL Server 2000.
try using a seed value in the RAND(seedInt). RAND() will only execute once per statement that is why you see the same number each time.
The Rand() function will generate the same random number, if used in a table SELECT query. Same applies if you use a seed to the Rand function. An alternative way to do it, is using this:
Got the information from here, which explains the problem very well.
It's as easy as:
And this will put a random number between 0-99 into a table:
When called multiple times in a single batch, rand() returns the same number.
I'd suggest using convert(
varbinary
,newid()
) as the seed argument:newid()
is guaranteed to return a different value each time it's called, even within the same batch, so using it as a seed will prompt rand() to give a different value each time.Edited to get a random whole number from 1 to 14.
Answering the old question, but this answer has not been provided previously, and hopefully this will be useful for someone finding this results through a search engine.
With SQL Server 2008, a new function has been introduced,
CRYPT_GEN_RANDOM(8)
, which uses CryptoAPI to produce a cryptographically strong random number, returned asVARBINARY(8000)
. Here's the documentation page: https://docs.microsoft.com/en-us/sql/t-sql/functions/crypt-gen-random-transact-sqlSo to get a random number, you can simply call the function and cast it to the necessary type:
or to get a
float
between -1 and +1, you could do something like this:Here the random number will come in between 20 and 30.
round
will give two decimal place maximum.If you want negative numbers you can do it with
Then the min value will be -60 and max will be -50.