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;
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.
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.
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.
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))”.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With