Generate unique random numbers using SQL

前端 未结 3 1730
抹茶落季
抹茶落季 2020-12-04 00:05

I have some SQL code which generates random numbers using the following technique:

DECLARE @Random1 INT, @Random2 INT, @Random3 INT, @Random4 INT, @Random5 I         


        
3条回答
  •  粉色の甜心
    2020-12-04 00:28

    I guess you could do something like this much simpler and much easier

    DECLARE @Upper INT;
    DECLARE @Lower INT;
    SET @Lower = 1;     /* -- The lowest random number */
    SET @Upper = 49;    /* -- The highest random number */
        
        
    SELECT @Lower + CONVERT(INT, (@Upper-@Lower+1)*RAND());
    

    For getting a random number without repetition, this will do the job

    WITH CTE 
    AS
    (
        SELECT  randomNumber, COUNT(1) countOfRandomNumber
        FROM (
        SELECT ABS(CAST(NEWID() AS binary(6)) %49) + 1 randomNumber
        FROM sysobjects
        ) sample
        GROUP BY randomNumber
    )
    SELECT TOP 5 randomNumber
    FROM CTE
    ORDER BY newid() 
    

    To set the highest limit, you can replace 49 with your highest limit number.

提交回复
热议问题