简体   繁体   English

如何在SQL Server 2008中编写存储过程,生成300万随机编号

[英]How to write stored procedure in SQL Server 2008 that generates 3 million random no

如何在SQL Server 2008中编写存储过程,在整数数据类型的两列中生成300万随机no。

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

[You may want to check the actual distribution of these numbers using a chi-square test] [您可能想要使用卡方检验来检查这些数字的实际分布]

UPDATE : The randomness of these may not meet the chi-square distribution test. 更新 :这些随机性可能不符合卡方分布测试。 I would advise Testing in for your circumstances. 我建议您根据自己的情况进行测试。

You can use a CTE, for example: 您可以使用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

This uses newid because the rnd function will return the same result for each recursive application of the CTE. 这使用newid因为rnd函数将为CTE的每个递归应用程序返回相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM