Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Microsoft SQL Server: Programming FAQ

Random Numbers

How Can I Generate a Series of Random Integers With T-SQL? by tlbroadbent
Posted: 3 Oct 01

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.

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
  Insert Into #t (RandNo) Values (null)
  Set @rec=@rec+1

Set @rec=1
While @rec<=@cnt
  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

Set nocount off

Select RandNo From #t

Drop Table #t

Back to Microsoft SQL Server: Programming FAQ Index
Back to Microsoft SQL Server: Programming Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close