Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Register Now and get your question answered!
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 How to get a Random (Ranged) Number based on a Per
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Starting Member

1 Posts

Posted - 12/05/2012 :  12:15:14  Show Profile  Reply with Quote


I have a table with 1 million records. For each of these records I want to generate a random number. This random number can be between 0 and 9 Each of these numbers, however, should get a chance to drop. For example, the 0 to have a 15% chance. The 1 is a 20% chance ...

How I would do it in T-SQL? I think of a scalar function. My approach:

DECLARE @RandomNumber float
DECLARE @RandomInteger int
DECLARE @MaxValue int
DECLARE @MinValue int
SET @MaxValue = 9
SET @MinValue = 0
SELECT @RandomNumber = RAND()
SELECT @RandomInteger = ((@MaxValue + 1) - @MinValue) * @RandomNumber + @MinValue
SELECT @RandomInteger

Now has the chance to be accommodated ...
But how .. ? :-(

Flowing Fount of Yak Knowledge

5155 Posts

Posted - 12/05/2012 :  13:08:51  Show Profile  Reply with Quote
One way (perhaps crude) is to have a table of discrete probabilities and then pick the value based on that as well. If I want to generate something between 0 and 5:
CREATE TABLE #tmp(Value INT, CumulativeProbability FLOAT);

SELECT MIN(VALUE) FROM #tmp WHERE CumulativeProbability >= 100*RAND()

I am giving a 74% probability to 100 in this case, so most of the results would be (should be) 5.
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.16 seconds. Powered By: Snitz Forums 2000