Thursday, March 18, 2010

Microsoft SQL - Return random number in Query in Microsoft SQL

After a lot of searching around for a random number generation function for Microsoft SQL views, and trying all kinds of different methods, and only finding very resource expensive methods for getting a random number for each line in a query result set, I stumbled on this very obvious solution in a forum. I unfortunately cannot remember the forum otherwise I would post the link but I figured it couldn't hurt posting this here.

We all know NEWID() function will return us a GUID, which is nicely random. So using this we can generate ourselves a nice random number.

Step 1. Convert the Guid to Binary using

Step 2. Great so we have random binary, which we can change into anything we basically want, so lets convert it to an in CAST(CAST(NEWID() AS VARBINARY) AS int)

Step 3. Ok we have a random number but it may be negative and we probably just need something positive, so lets do ABS(CAST(CAST(NEWID() AS VARBINARY) AS int))

Step 4. Last step is to limit our Random number, The mod operator will help us here so lets say we want a random number up to 1000 we go ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 1000

So if you have a Northwind database and run

Select ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 10000 as RANDOMNUMBER,* from dbo.Customers

You will get a random number for each row in the Customer table in the database

You can also use this in a View and it works perfectly.

Hope this makes someone else's search a bit less frustrating than mine was.