Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How Can I Generate a Series of Random Integers With T-SQL?

Random Numbers

How Can I Generate a Series of Random Integers With T-SQL?

by  tlbroadbent  Posted    (Edited  )

Here is a stored procedure that will generate a series of random numbers and return them in a result set.

/*
This SQL Server stored procedure returns a result set
containing a series of random integers

Inputs are:
@begin_no - lowest number to be generated,
@end_no - highest number to be generated

Calling syntax:
Exec sp_GenerateRandomNumberResultSet Begin, End

Created by Terry L. Broadbent, Oct 3 2001

Please inform me of any bugs encountered. Comments and suggestions for improvement are encouraged.
*/
[tt]
CREATE procedure sp_GenerateRandomNumberResultSet
@begin_no int=1, @end_no int=100 As

Set nocount on

Declare @rn int, @rec int, @cnt int
Set @cnt=@end_no-@begin_no+1

Create Table #t (RecNo int identity(1,1), RandNo int null)

Set @rec=1
While @rec<=@cnt
Begin
Insert Into #t (RandNo) Values (null)
Set @rec=@rec+1
End

Set @rec=1
While @rec<=@cnt
Begin
Set @rn=rand()*@cnt+@begin_no
If @begin_no<0 Set @rn=@rn-1
Update #t Set RandNo=@rn
Where RecNo=@rec
And @rn Not In
(Select RandNo
From #t Where RandNo Is Not Null)
If @@rowcount>0 Set @rec=@rec+1
End

Set nocount off

Select RandNo From #t

Drop Table #t
Go[/tt]
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top