随机数字SQL

时间:2013-02-15 11:54:45

标签: tsql

我已经能够使用以下代码随机化日期

DATEADD (day, CAST (RAND () * 365 as int), '2010-1-1') 

我现在需要为1到7以及1到126之间的数字执行此操作。

你能帮忙吗?

SELECT        'Booking_' + Cast(Seed.Seed as varchar(25)) as BookingNo,
DATEADD(day, ABS(CHECKSUM(NEWID()) % 800), '1 Jan 2010') as ArrivalDate,
DATEADD (day, CAST (RAND () * 365 as int), '2010-1-1') % 6 + 1 as PitchType

FROM            Seed CROSS JOIN
                         Seed AS Seed_1 CROSS JOIN
                         Seed AS Seed_2 CROSS JOIN
                         Seed AS Seed_3 CROSS JOIN
                         Seed AS Seed_4 CROSS JOIN
                         Seed AS Seed_5

2 个答案:

答案 0 :(得分:3)

您可以使用:

SELECT CAST(RAND(CHECKSUM(NEWID())) * 7 + 1 AS INT)

其中7是随机性的上限。

答案 1 :(得分:0)

如果您有一个数字表,这很简单,例如内置数字表

介于1到7之间

select top 1 number
from master..spt_values
where type ='p'
and number between 1 and 7
order by newid()

介于1到126之间

select top 1 number
from master..spt_values
where type ='p'
and number between 1 and 126
order by newid()

继续执行查询,您将看到每次都会得到不同的数字