如何为ID字段创建随机数在SQL Server中?
我想在1000到9999之间创建随机数。
如何创建此结构?
答案 0 :(得分:2)
RAND
是内置函数。它应该满足您的需求。这应该可以为您提供所需的结果:select cast(rand() * 8999 + 1000 as int)
http://msdn.microsoft.com/en-us/library/ms177610%28v=SQL.105%29.aspx
答案 1 :(得分: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;
答案 2 :(得分: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