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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Get random value

Author  Topic 

shapper
Constraint Violating Yak Guru

450 Posts

Posted - 2008-02-24 : 17:38:18
Hello,

How to get a random bit and a random int?

Thanks,
Miguel

tprupsis
Yak Posting Veteran

88 Posts

Posted - 2008-02-24 : 18:05:13
You can use the rand() function to do this. Rand() returns a float between 0 and 1 so multiplying by a factor and then converting to int should work to return a random int: convert(int, 1000*rand())

As far as returning a bit, just use 2 as your factor.

Go to Top of Page

sodeep
Master Smack Fu Yak Hacker

7174 Posts

Posted - 2008-02-24 : 18:05:16

This will work for random int

DECLARE @Random int;
DECLARE @Upper int;
DECLARE @Lower int

-- This will create a random number between 1 and 999
SET @Lower = 1 -- The lowest random number
SET @Upper = 999 -- The highest random number
SELECT @Random = Round(((@Upper - @Lower -1) * Rand() + @Lower), 0)
SELECT @Random
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2008-02-25 : 03:46:41
quote:
Originally posted by sodeep


This will work for random int

DECLARE @Random int;
DECLARE @Upper int;
DECLARE @Lower int

-- This will create a random number between 1 and 999
SET @Lower = 1 -- The lowest random number
SET @Upper = 999 -- The highest random number
SELECT @Random = Round(((@Upper - @Lower -1) * Rand() + @Lower), 0)
SELECT @Random


or
select abs(checksum(newid()))%1000

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -