0

I need to generate random values for multiple rows in a column. The random values need to be in the range of 0.005 and 0.015 inclusive.

I have tried using the abs(checksum(newID()) but I am not sure how to specify a range using that.

3 Answers 3

1

You can use rand() and arithmetic:

select rand(checksum(newID())) * 0.01 + 0.005
Sign up to request clarification or add additional context in comments.

Comments

0

You can give a range like this by using the RAND() function.

Please execute SQL and you can see. The number that comes will be within the range.

SQL:

SELECT RAND()*(0.015-0.005)+0.005 as randomNumber

Here, 0.015 and 0.005 are range number.

SQL output

|----|-------|----------------------|
|id  |empCode| randomNumber         |
|----|------------------------------|
|1   | 0001  | 0.01245219297469798  |
|----|-------|----------------------|
|2   | 0002  | 0.010188965811570142 |
|----|-------|----------------------|

Hopefully, your problem will be resolved.

3 Comments

This will generate the same random number for every row. Not what I am looking for.
@Franktank24 I have executed SQL Query and a unique number is generated for each line from the query.
@Franktank24 I have added the output of the SQL query in the above answer, please check.
0

Late to the game... but here's a good solution: Random number in range.

ABS(CHECKSUM(NEWID()))%<Number of Values in Range> + <Lowest Value in Range> + 1

So here we get a RandomNumber for each row with values between 10 and 20

SELECT FirstName,MiddleName,LastName, ABS(CHECKSUM(NEWID()))%10 + 11 AS RandomNumber
FROM Person.Person

Taken from https://sqlundercover.com/2017/06/22/generating-random-numbers-for-each-row-over-a-specified-range-and-other-funky-stuff-you-can-do-with-them/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.