Technical Article

random integer number scalar function

,

simply create the function on the database and access it like this:

select dbo.fx_getrandomnumber(500, 300, rand())

if @maxvalue is null and @minvalue is null then a random number between 0 and a hundred is returned.

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        CHRIS MORTON
-- Create date: 19-11-08
-- Description:    GENERATES A RANDOM INTEGER BETWEEN A CERTAIN RANGE. DEFAULT RANDOM NUMBER BETWEEN 0 - 100
-- =============================================
ALTER FUNCTION [dbo].[FX_GetRandomNumber]
 (
 @MaxValue BIGINT,
 @MinValue BIGINT,
 @RandomNumber FLOAT 
 )
RETURNS BIGINT
AS BEGIN
     
 DECLARE @RandomInteger BIGINT
 
IF @MaxValue IS NULL
BEGIN
SET @MaxValue = 100
END
IF @MinValue IS NULL
BEGIN
SET @MinValue = 0
END
 
 
 SELECT @RandomInteger = ( ( @MaxValue + 1 ) - @MinValue ) * @RandomNumber
 + @MinValue

 RETURN @RandomInteger
    
 END

Rate

2.5 (4)

You rated this post out of 5. Change rating

Share

Share

Rate

2.5 (4)

You rated this post out of 5. Change rating