Monday 19 September 2011

SQL Server - Random Number

Frequently I get asked by my colleagues on random number generation in SQL Server. The novices are puzzled why the Rand() function returns the same number when used in a select statement to generate data.

To generate random number in a single select statement within a range, I always use the below method.


 CREATE VIEW vwRandNumber  
 AS  
      SELECT RAND() as RandNumber  
 GO  
 CREATE function dbo.fnRand() RETURNS FLOAT   
 AS   
 BEGIN   
      RETURN (SELECT RandNumber FROM vwRandNumber)   
 END  
 GO  
 CREATE FUNCTION fn_RandNumber_Int(@Min int, @Max int)  
 RETURNS INT  
 AS  
 BEGIN  
      RETURN @Min + (select dbo.fnRand()) * (@Max-@Min)  
 END  
 GO  
 CREATE FUNCTION fn_RandNumber_Float(@Min float, @Max float)  
 RETURNS float  
 AS  
 BEGIN  
      RETURN @Min + (select dbo.fnRand()) * (@Max-@Min)  
 END  
 GO  
 SELECT TOP 10 dbo.fn_RandNumber_Int (10, 200) FROM sys.objects  
 SELECT TOP 10 dbo.fn_RandNumber_Float (10.1, 200.7) FROM sys.objects  
 GO  

No comments:

Post a Comment