Technical Article

Random Number Generator

,

Often the RAND() function is predictable based on the seed. This stored procedure generates a pretty good random integer because the seed itself is quite unpredictable. You can’t put this in a UDF since it is indeterminate due to the RAND and GETDATE() functions used.

CREATE PROCEDURE [dbo].[RandomInteger$Produce]
(@RandomInteger INT OUTPUT)
AS
SET NOCOUNT ON
-- We'll use this seed twice below
DECLARE @SEED FLOAT

-- In rare instances, the right six digits will include the decimal - AVOID THIS!
WHILE ISNUMERIC(RIGHT(CONVERT(VARCHAR(11),CONVERT(INT,ROUND(1000000000*@SEED,0))),6))=0
BEGIN
 SELECT @SEED = RAND(DATEPART(MS,GETDATE()))
END

SELECT @RandomInteger = 
-- convert it from a FLOAT to an INT
CONVERT(INT,
-- get the round of the RAND multiplied by the largest integer
ROUND(2147483647*
-- Get the upper RAND of the random integer
RAND(
-- get the right six numerals of the INT of the @SEED and conv to INT
CONVERT(INT,RIGHT(CONVERT(VARCHAR(11),CONVERT(INT,ROUND(1000000000*@SEED,0))),6))),0))
-- multiply by 1 or -1 based on modulo%2 of our random @SEED
* CASE WHEN CONVERT(INT,ROUND(2147483647*@SEED,0))%2  = 1 THEN 1 ELSE -1 END 
RETURN
GO

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating