SQL Server:如何将随机整数插入表中?

时间:2011-06-16 12:04:11

标签: sql sql-server sql-server-2005 tsql sql-server-2008

我有一个像这样的测试表

CREATE TABLE #temp (
    rid INT IDENTITY (1, 1) NOT NULL,
    val INT NULL,
    CONSTRAINT pk_temp_rid PRIMARY KEY (rid)
);

SQL Server中有哪些不同的方法可以将随机整数插入此表中(例如1000行)。循环,交叉连接还是什么?

我试过了,但结果不正确

DECLARE @val AS INT = 1;

WHILE @val <= 1000
    BEGIN
        INSERT #temp (val)
        SELECT RAND(@val);
        SET @val = @val + 1;
    END

SELECT *
FROM   #temp;

4 个答案:

答案 0 :(得分:7)

来自SQL SERVER – Random Number Generator Script

SELECT randomNumber, COUNT(1) countOfRandomNumber
FROM (SELECT ABS(CAST(NEWID() AS binary(6)) % 1000) + 1 randomNumber
      FROM sysobjects) sample
GROUP BY randomNumber;

编辑:为了澄清,脚本正在对每行生成的随机数进行分组。因此,不保证结果总数。不过,您可以确定永远不会获得比SELECT COUNT(*) FROM sysobjects更多的行。

答案 1 :(得分:7)

这也在上面做了

Insert Into @t
Select Cast(rand(checksum(newid()))*1000000  as int)
go 1000

请参阅此链接:https://www.mssqltips.com/sqlservertip/1467/populate-a-sql-server-column-with-a-sequential-number-not-using-an-identity/

答案 2 :(得分:3)

您可以使用select CAST(RAND() * 1000000 AS INT) AS [RandomNumber]生成或选择随机整数。 所以完整的查询将是这样的:

    DECLARE @t TABLE( randnum float )
DECLARE @cnt INT; SET @cnt = 0
WHILE @cnt <=10000
BEGIN
SET @cnt = @cnt + 1
INSERT INTO @t
SELECT RAND( (DATEPART(mm, GETDATE()) * 100000 )
+ (DATEPART(ss, GETDATE()) * 1000 )
+ DATEPART(ms, GETDATE()) )
END
SELECT randnum, COUNT(*)
FROM @t
GROUP BY randnum

问候..

答案 3 :(得分:2)

我认为`while会有效。你很近。

DECLARE @val AS INT = 1;

WHILE @val <= 1000
BEGIN
    INSERT #temp (val)
    SELECT cast((RAND()*1000) as int);
    SET @val = @val + 1;
END

SELECT *
FROM   #temp;