posted 5/8/2011 by timmurphy - Views: [1335]
Here is an interesting and simple way of generating a random value for each row in a SELECT. I needed to do this for a project where I needed to assign a random integer from 1 to 5.
It works by casting the NEWID as varbinary and using it as a seed for the RAND function. Without the seed the RAND function would generate the same random number for each row.
You can play with it here using the AdventureWorks database.
USE AdventureWorks
SELECT CAST(RAND(CAST(NEWID()AS VARBINARY)) * 5 + 1 AS INT) AS RandomID
,FirstName
FROM Person.Contact
RandomID
FirstName
5
Gustavo
2
Catherine
1
Kim
4
Humberto
Pilar
Frances
Margaret
Carla
3
Jay
Ronald
Samuel
James