Free Information Technology Magazines and eBooks

Thursday, August 06, 2009

How to get a random number from 1 to N in SQL Server

If you want to pick a random number from a range for example 1 to 1000 in SQL, you can use the RAND() that returns a pseudo-random float value plus the NEWID() function which creates a unique value of type uniqueidentifier. Here is a short SQL sniffet that picks a random number from 1 to 1000.


DECLARE @RandomNum int
SET @RandomNum = CONVERT(int, 1 + 1000*RAND(CHECKSUM(NEWID())))
PRINT @RandomNum


For more SQL Coding Tips, subscribe now.

3 comments:

aileen said...

I recently came accross your blog and have been reading along. I thought I would leave my first comment. I dont know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.


Susan

http://dclottery.info

Fryan Valdez said...

@susan
Hi susan, thanks for the compliment. rest assured that i will blog more quality contents everyday =)

Anonymous said...

really????
well goodluck!!!