How would you create a function that returns a random number between two number?
example syntax
RandBetween(3,300)
The RAND() function returns a random number between 0 (inclusive) and 1 (exclusive).
To create a random integer number between two values (range), you can use the following formula: SELECT FLOOR(RAND()*(b-a+1))+a; Where a is the smallest number and b is the largest number that you want to generate a random number for.
RAND() function : This function in SQL Server is used to return a random decimal value and this value lies in the range greater than and equal to zero (>=0) and less than 1. If we want to obtain a random integer R in the range i <= R < j, we have to use the expression “FLOOR(i + RAND() * (j − i))”.
One simple method is to make use of RAND() function available in SQL Server. RAND() function simply generate a decimal number between 0 (inclusive) and 1 (exclusive). The logic is to multiply value returned by RAND() by 1 billion so that it has enough digits and apply LEFT function to extract 6 digits needed.
How about
RAND()
(which returns a value between 0 and 1 (exclusive).i.e.
SELECT CAST(RAND() * 298 + 3 AS INT)
Fiddle
(Edit Also see @ivo's answer for how to turn this into a user defined function)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With