如何在SQL Server 2008中编写存储过程,在整数数据类型的两列中生成300万随机数。
答案 0 :(得分:5)
SELECT TOP 3000000
ABS(CHECKSUM(NewId())) As RndCol1,
ABS(CHECKSUM(NewId())) AS RndCol2
FROM
sys.objects s1
CROSS JOIN sys.objects s2
CROSS JOIN sys.objects s3
CROSS JOIN sys.objects s4
[您可能需要使用卡方检验来检查这些数字的实际分布]
更新:这些随机性可能不符合卡方分布测试。我建议您根据自己的情况进行测试。
答案 1 :(得分:1)
您可以使用CTE,例如:
create procedure dbo.GiveMeRandomNumbers
as
begin
with qry as (
select CAST(CAST(NEWID() AS VARBINARY) AS INT) as col1
, CAST(CAST(NEWID() AS VARBINARY) AS INT) as col2
, 0 as i
union all
select CAST(CAST(NEWID() AS VARBINARY) AS INT) as col1
, CAST(CAST(NEWID() AS VARBINARY) AS INT) as col2
, i + 1
from qry
where i < 3000000
)
select col1, col2
from qry
option (maxrecursion 0)
end
这使用newid
,因为rnd
函数将为CTE的每个递归应用返回相同的结果。