How to populate a database column with random numbers

前端 未结 2 705
日久生厌
日久生厌 2021-01-16 01:51

How do I populate a int column, currently empty, with random numbers with no duplicates?

2条回答
  •  执笔经年
    2021-01-16 02:28

    I suppose you could make the column a primary key to prevent duplicates, though that's kind of a hack. You can remove the key later.

    ---- Create the variables for the random number generation
    DECLARE @Random INT;
    DECLARE @Upper INT;
    DECLARE @Lower INT;
    DECLARE @Index integer
    
    ---- This will create a random number between 1 and 999
    SET @Lower = 1 ---- The lowest random number
    SET @Upper = 999 ---- The highest random number
    SET @Index = 0 --- A while loop counter
    
    --- Loop from 0 to 10
    WHILE @Index < 10
    BEGIN
      SELECT 'loop counter = ', @index
      SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)
      --Insert @Random here.
      SET @index = @index + 1
    END
    

提交回复
热议问题