0

如何在 SQL Server 中为 ID 字段创建随机数?

我想创建 1000 到 9999 之间的随机数。

如何创建这个结构?

4

3 回答 3

2

RAND是一个内置函数。它应该满足您的需求。这应该会给你想要的结果:select cast(rand() * 8999 + 1000 as int)

http://msdn.microsoft.com/en-us/library/ms177610%28v=SQL.105%29.aspx

于 2013-01-08T03:59:11.143 回答
1

您没有提到是否要生成唯一非重复的随机数。

DECLARE @Random INT;
DECLARE @Upper INT;
DECLARE @Lower INT;

---- This will create a random number between 1 and 999
SET @Lower = 1000 ---- The lowest random number
SET @Upper = 9999 ---- The highest random number
SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)
SELECT @Random;

资源

于 2013-01-08T04:30:02.450 回答
0

另一种方法

select number/power(10,len(number)-4) as number from
(
select top 10000 abs(checksum(newid())) as number 
from sysobjects s1 cross join sysobjects s2
) as T

另请参阅此http://beyondrelational.com/modules/2/blogs/70/posts/10810/generating-random-numbers-part-ii.aspx

于 2013-01-08T08:01:50.310 回答