表中的每一行都需要一个不同的随机数。下面的代码对每一行使用相同的随机值。
SELECT table_name, RAND() magic_number
FROM information_schema.tables
我想从中得到一个INT或FLOAT。接下来,我将使用这个随机数从已知日期创建一个随机日期偏移量,例如从开始日期的1-14天偏移量。
这是为Microsoft SQL Server 2000。
表中的每一行都需要一个不同的随机数。下面的代码对每一行使用相同的随机值。
SELECT table_name, RAND() magic_number
FROM information_schema.tables
我想从中得到一个INT或FLOAT。接下来,我将使用这个随机数从已知日期创建一个随机日期偏移量,例如从开始日期的1-14天偏移量。
这是为Microsoft SQL Server 2000。
当前回答
如果你想生成一个1到14之间的随机数。
SELECT CONVERT(int, RAND() * (14 - 1) + 1)
OR
SELECT ABS(CHECKSUM(NewId())) % (14 -1) + 1
其他回答
生成1000到9999之间的随机数,包括:
FLOOR(RAND(CHECKSUM(NEWID()))*(9999-1000+1)+1000)
"+1" -包含上限值(上例为9999)
您是否在每一行中都有一个整数值,可以作为种子传递给RAND函数?
要得到1到14之间的整数,我相信这是可行的:
FLOOR( RAND(<yourseed>) * 14) + 1
看看SQL Server -设置基于随机数有一个非常详细的解释。
综上所述,下面的代码生成了一个0到13之间的随机数,包括均匀分布:
ABS(CHECKSUM(NewId())) % 14
要更改范围,只需更改表达式末尾的数字。如果你需要一个同时包含正数和负数的范围,要格外小心。如果你做错了,可能会重复计算数字0。
A small warning for the math nuts in the room: there is a very slight bias in this code. CHECKSUM() results in numbers that are uniform across the entire range of the sql Int datatype, or at least as near so as my (the editor) testing can show. However, there will be some bias when CHECKSUM() produces a number at the very top end of that range. Any time you get a number between the maximum possible integer and the last exact multiple of the size of your desired range (14 in this case) before that maximum integer, those results are favored over the remaining portion of your range that cannot be produced from that last multiple of 14.
例如,假设Int类型的整个范围只有19。19是最大的整数。当CHECKSUM()的结果为14-19时,这些结果对应于结果0-5。这些数字比6-13更受欢迎,因为CHECKSUM()生成它们的可能性是前者的两倍。更容易直观地演示这一点。下面是我们的虚整数范围的全部可能结果集:
Checksum Integer: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Range Result: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 0 1 2 3 4 5
你可以在这里看到,产生某些数字的机会比产生其他数字的机会更多:偏见。幸运的是,Int类型的实际范围要大得多……在大多数情况下,这种偏差几乎是无法检测到的。但是,如果您发现自己正在为严肃的安全代码执行此操作,则需要注意这一点。
select ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) as [Randomizer]
一直对我有效吗
您需要为每一行调用RAND()。这里有一个很好的例子
https://web.archive.org/web/20090216200320/http://dotnet.org.za/calmyourself/archive/2007/04/13/sql-rand-trap-same-value-per-row.aspx