小编典典

如何用随机数填充数据库列

sql

如何填充一个int列(当前为空),其中包含不带重复项的随机数?


阅读 209

收藏
2021-04-07

共1个答案

小编典典

我想您可以使该列成为防止重复的主键,尽管这是一种hack。您可以稍后删除密钥。

---- 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
2021-04-07