Monday, February 4, 2013

SQL Code Snippets - Assign Random Number within Range to a set of Records

So lets say we want to assign a random number from 1 to 4 to every record coming out of a system.  How do we do this?

Intuitively if we want 100 random numbers we would use


select top 100 rand() from sysobjects

And then manipulate it some way, like   

select top 100  cast(((4 + 1) - 1) * rand() + 1 as int)  from sysobjects

Unfortunately that does not work, so this is a better way.

ABS(CHECKSUM(NewId()) % <range>) + <offset from 0> --- Note the + 1 makes it so that it cannot be 0.

The Absolute value is because checksums can be positive or negative (the range returned is + or - the <range> value and falls on the number line from -<range> + 1 to <range> -1 So if we set range to 4 we get the numbers  -3, -2, -1,0,1,2,3 after applying absolute value we get 0,1,2,3 after applying the offset we get 1,2,3,4


An example you can run to see this for yourself:

select
              top 100 id,name,ABS(CHECKSUM(NewId()) % 4) + 1 as [MyRandomNumber]
from sysobjects


id
name
MyRandomNumber
3
sysrscols
3
5
sysrowsets
4
7
sysallocunits
4
8
sysfiles1
1
17
syspriorities
1
19
sysfgfrag
1
23
sysphfg
1
24
sysprufiles
4
25
sysftinds
2
27
sysowners
2

No comments:

Post a Comment