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

时间:2009-05-10 02:00:53

标签: sql-server database sql

如何使用没有重复项的随机数填充当前为空的int列?

2 个答案:

答案 0 :(得分:9)

如果这是您添加了新INT列的现有表,则可以执行以下操作:

UPDATE MyTable
SET MyIntColumn = CONVERT(int, RAND(CHECKSUM(NEWID())) * 10000);

这将使用1到10000之间的随机数填充空列。

答案 1 :(得分:1)

我想你可以将列作为主键来防止重复,尽管这是一种黑客行为。您可以稍后删除密钥。

---- 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