Generate unique random numbers using SQL

前端 未结 3 1719
抹茶落季
抹茶落季 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:08

    For Laravel:

     public function generatUniqueId()
        {
            $rand = rand(10000, 99999);
            $itemId = $rand;
            while (true) {
                if (!BookItem::whereBookItemId($itemId)->exists()) {
                    break;
                }
                $itemId = rand(10000, 99999);
            }
    
            return $itemId;
        }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-04 00:28

    You can use Rand() function .

    select CEILING(RAND() *<max of random numbers))
    
    0 讨论(0)
提交回复
热议问题