CREATE PROCEDURE [dbo].[spCreateRandom]
    @Lower NUMERIC,
    @Upper NUMERIC,
    @LotteryKind TINYINT,
    @StartDate SMALLDATETIME,
    @EndDate SMALLDATETIME,
    @Random NUMERIC OUTPUT
AS
SET @Random = ROUND(((@Upper - @Lower - 1) * RAND() + @Lower), 0);
IF (EXISTS
(
    SELECT AutoId
    FROM dbo.Tbl_RandomLottery
    WHERE (
              @LotteryKind = 0
              AND CONVERT(VARCHAR(10), StartDate, 111) >= @StartDate
              AND CONVERT(VARCHAR(10), EndDate, 111) <= @EndDate
          )
          OR (
                 @LotteryKind = 1
                 AND StartFactorNumber >= @Lower
                 AND EndFactorNumber <= @Upper
             )
             AND Flag = '1'
             AND Id_Havaleh = @Random
)
   )
    EXECUTE spCreateRandom @Lower,
                           @Upper,
                           @LotteryKind,
                           @StartDate,
                           @EndDate,
                           @Random = @Random OUTPUT;
RETURN @Random;
