Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RANDBETWEEN for SQL Server 2012

Tags:

sql

sql-server

How would you create a function that returns a random number between two number?

example syntax

RandBetween(3,300)

like image 998
Bill Avatar asked Jun 02 '15 16:06

Bill


People also ask

How do I select a random number in SQL Server?

The RAND() function returns a random number between 0 (inclusive) and 1 (exclusive).

How do I generate a random number between ranges in SQL Server?

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.

How do I use rand in SQL?

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))”.

How do you generate a 6 digit random number in SQL?

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.


1 Answers

How about

  • Use RAND() (which returns a value between 0 and 1 (exclusive).
  • multiply by 298 (since you want a dynamic range of [300-3] = 297 + 1)
  • add 3 to Offset
  • and cast to INT?

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)

like image 181
StuartLC Avatar answered Sep 26 '22 02:09

StuartLC