SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Generating random numbers (exclude negatives)
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Rock_query
Yak Posting Veteran

52 Posts

Posted - 05/02/2013 :  20:27:26  Show Profile  Reply with Quote
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

547 Posts

Posted - 05/02/2013 :  20:55:02  Show Profile  Reply with Quote
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.


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


Edited by - MuMu88 on 05/02/2013 20:59:55
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

Sweden
30218 Posts

Posted - 05/03/2013 :  07:51:37  Show Profile  Visit SwePeso's Homepage  Reply with Quote
ABS(CHECKSUM(NEWID())) % 1000



N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000