Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: how to insert random integers into table?

I have a test table like this

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

What are the different methods in SQL Server to insert random integers into this table (e.g for 1000 rows). While loop, cross join or what?

I tried this but the result is not correct

DECLARE @val AS INT = 1;

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

SELECT *
FROM   #temp;
like image 464
jrara Avatar asked Jun 16 '11 12:06

jrara


People also ask

How do I insert a random number in a table in SQL?

To create a random integer number between two values (range), you can use the following formula: SELECT FLOOR(RAND()*(b-a+1))+a; Where a is the smallest number and b is the largest number that you want to generate a random number for.

How do I insert a random value in a column in SQL?

SQL RAND() exampleSELECT RAND(); SELECT RAND(5); As you can see, in the first example, the RAND() function generates a random number in decimals between 0 to 1. Each time you execute the statement, it returns different random values.

Is there a random number generator in SQL?

SQL Server has a built-in function that generates a random number, the RAND() mathematical function. The RAND math function returns a random float value from 0 through 1. It can take an optional seed parameter, which is an integer expression (tinyint, smallint or int) that gives the seed or start value.

How do I use rand in SQL?

RAND() function : This function in SQL Server is used to return a random decimal value and this value lies in the range greater than and equal to zero (>=0) and less than 1. If we want to obtain a random integer R in the range i <= R < j, we have to use the expression “FLOOR(i + RAND() * (j − i))”.


2 Answers

This also done above

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

See this link : https://www.mssqltips.com/sqlservertip/1467/populate-a-sql-server-column-with-a-sequential-number-not-using-an-identity/

like image 132
SPE109 Avatar answered Oct 16 '22 11:10

SPE109


From 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;

EDIT: Just to clarify, the script is grouping on the random number that was generated per row. So the total number of results is not guaranteed. You can be sure you'll never get more rows than SELECT COUNT(*) FROM sysobjects, though.

like image 34
Yuck Avatar answered Oct 16 '22 13:10

Yuck