I needed to generate a massive amount of random numbers.
There are two ways to do it in SQL Server 2005 and above that I know of.
The first one is to use the rand function which returns a number between 0 and 1,
this is very convinient since you can limit your range of values to a specific range (though if you want negative numbers, it is a bit more tricky).
The problem with rand() is that it returns the same value for each time you invoke it in a SQL statement, for example if I run
select rand()*100
from my_table
I get back the same results for all the records. This means that if I want to generate different random values I would have to use a loop.
The second option is to use the newid() function which generates a uniqueidentifier. This has two great advantages over using rand():
1. it will generate a unique value for each record in the result set, so you can use a single statement without using loops.
2. it is easier to limit the range of generated values to a range of a specific data type, for example
select cast(cast(newid() as binary(4)) as int)
will return random integers.
If you want to limit the values to a specific range you can always use the % operator, for example
select cast(cast(newid() as binary(4)) as int)%7
will always return numbers between -6 and 6
That is it for now
Take Care