Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Generating random numbers (exclude negatives)

Author  Topic 

Rock_query
Yak Posting Veteran

55 Posts

Posted - 2013-05-02 : 20:27:26
In the following statement I am generating a random number. But sometimes, I get a negative number. So to handle that, I am using an IIF statement and multiplying by -1 to convert a negative to a positive. Then if it is already positive, leave it that way.

SELECT IIF(CHECKSUM(NEWID())/10000000<0,(CHECKSUM(NEWID())/10000000)*-1,CHECKSUM(NEWID())/10000000)

When I execute this statement, I am still getting negative numbers. It's as if the IIF statement is being ignored. What am I doing wrong?

MuMu88
Aged Yak Warrior

549 Posts

Posted - 2013-05-02 : 20:55:02
Everytime you call NEWID() function a new random number gets generated so in your query you are generate three different random numbers.

You may want to do just the following to get what you need: ABS() gives you the absolute value.
[CODE]

SELECT ABS(CHECKSUM(NEWID())/10000000)

[/CODE]
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2013-05-03 : 07:51:37
ABS(CHECKSUM(NEWID())) % 1000



N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page
   

- Advertisement -