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.
No comments:
Post a Comment