Search This Blog

Google Analytics

Sunday, August 05, 2007

Microsoft SQL Server - Get Random Integer from a Range

I created the below script today as an answer to one of the SQL question in EE. I thought it may come handy.

Basically, the below Stored Procedure will generate a random integer from an integer range. The code is tested using SQL Server 2005.

IF ISNULL(object_id('cspGenRandomInteger'),0)<>0 DROP PROC cspGenRandomInteger
GO 
 
CREATE PROC cspGenRandomInteger(@MinValue int, @MaxValue int, @RandomInteger int output, @DebugMode bit=0)
AS
BEGIN
    SET NOCOUNT ON
 
    DECLARE @RandomNumber float
 
    SELECT @RandomNumber = RAND(CONVERT(VARBINARY, NEWID()))
 
    SELECT @RandomInteger = ((@MaxValue + 1) - @MinValue) * @RandomNumber + @MinValue
    IF @DebugMode = 1 SELECT @RandomNumber RandomNumber, @RandomInteger RandomInteger
END
GO
 
IF ISNULL(object_id('cspGenRandomInteger'),0)<>0 GRANT EXECUTE ON cspGenRandomInteger TO PUBLIC
GO
 
-- Test SP
DECLARE @RandomInteger int
DECLARE @MinValue int, @MaxValue int
SELECT @MinValue = 1, @MaxValue = 10
-- Add last parameter @DebugMode=1 for debugging purposes
--EXEC cspGenRandomInteger @MinValue, @MaxValue, @RandomInteger output, 1
EXEC cspGenRandomInteger @MinValue, @MaxValue, @RandomInteger output
PRINT @RandomInteger
 
IF ISNULL(object_id('cspGenRandomInteger'),0)<>0 DROP PROC cspGenRandomInteger
GO

1 comment:

  1. create function fnGenRandomInteger(@MinValue int, @MaxValue int, @Seed float)
    returns int
    as
    begin
    return ((@MaxValue + 1) - @MinValue) * @Seed + @MinValue
    end
    go
    select dbo.fnGenRandomInteger(1,3,RAND(CONVERT(VARBINARY, NEWID())))

    ReplyDelete

Do provide your constructive comment. I appreciate that.

Popular Posts