如何在SQL Server中生成十个绝对随机数?

时间:2011-09-03 04:29:54

标签: sql-server

如何在SQL Server中生成10个绝对随机数?

我尝试了select ABS(CHECKSUM(rand()))

但我无法控制数字位数!!

3 个答案:

答案 0 :(得分:6)

RAND()返回0到1之间的数字。因此您不需要调用ABS()。您可以通过将RAND的结果乘以10得到10位(10000000000)的幂来获得10位随机整数,然后舍入结果(我在下面的示例中选择了楼层,但您可以使用CEILING()或ROUND()) 。由于10位数字处于int数据类型的限制,因此我将POWER()强制为bigint。

SELECT FLOOR(RAND() * POWER(CAST(10 as BIGINT), 10))

参考

http://msdn.microsoft.com/en-us/library/ms177610.aspx
http://msdn.microsoft.com/en-us/library/ms187745.aspx

答案 1 :(得分:3)

您可以强制随机数落在一个范围内,使其具有相同的位数,例如:

SELECT 10000 + CONVERT(INT, (99000-10000+1)*RAND())


SELECT len(CAST(10000 + CONVERT(INT, (99000-10000+1)*RAND()) as VARchar(20))) --5 digits

因为rand()总是< 0 => (99000-10000+1)*RAND()始终是[0,89,001)因此您最终会得到10,000到89,000之间的随机数,这些数字都有5位数。

Other techniques for random numbers in general are here.

答案 2 :(得分:1)

10个随机数=)

[注意:我很奇怪......我知道]

SELECT 
  CAST((1/rand()*1000) AS INT) % 10 AS One,
  CAST((1/rand()*1000) AS INT) % 10 AS Two,
  CAST((1/rand()*1000) AS INT) % 10 AS Three,
  CAST((1/rand()*1000) AS INT) % 10 AS Four,
  CAST((1/rand()*1000) AS INT) % 10 AS Five,
  CAST((1/rand()*1000) AS INT) % 10 AS Six,
  CAST((1/rand()*1000) AS INT) % 10 AS Seven,
  CAST((1/rand()*1000) AS INT) % 10 AS Eight,
  CAST((1/rand()*1000) AS INT) % 10 AS Nine,
  CAST((1/rand()*1000) AS INT) % 10 AS Ten

结果:

One Two  Three  Four    Five    Six  Seven  Eight   Nine    Ten
 6   0     1      2      1       0     1      5      2       5