Tuesday, May 5, 2009

How to generate random numbers in t-sql? Is there any built-in logic or keyword for Random? Yes, the answer is below.
DECLARE @mx int, @mn int;
SELECT @mx = MAX(EmployeeID) FROM Employee;
SELECT @mn = MIN(EmployeeID) FROM Employee;
SELECT EmployeeID,EmployeeName FROM Employee WHERE EmployeeID = ROUND(@mn + (RAND() * (@mx-@mn)),0);
RAND() is the function which gives you the random number between 0 and 1. So, depends on the minimum and maximum numbers, it will give you the random number. Hope this is what you are looking for.

1 comment: