Monday, January 17, 2011

SQL Server: Which is the Best Way to Generate Random Number


Following are two commonly used methods to generate random numbers. My question is that which one is better and why? I will post your answer on this blog with due credit.
Method-1:
By using RAND () built-in function
DECLARE @n AS INT;
SET @n = 1000;
SELECT CAST(RAND()*@n AS INT) + 1
Method-2:
By using CHECKSUM built-in function
DECLARE @n AS INT;
SET @n = 1000;
SELECT 1+ABS(CHECKSUM(NEWID())) % @n

No comments:

Post a Comment

All suggestions are welcome