INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Member Login

HANDLE


PASSWORD
Remember Me
Forgot Password?

Come Join Us!

  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • Turn Off Ad Banners
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

E-mail*
Handle

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

Partner With Us!

"Best Of Breed" Forums Add Stickiness To Your Site
Partner Button
(Download This Button Today!)

Member Feedback

"...Keep up the good work - excellent site - i'd been looking for something like this for ages !..."

Geography

Where in the world do Tek-Tips members come from?

Microsoft SQL Server: Programming FAQ

Random Numbers

How Can I Generate a Series of Random Integers With T-SQL?
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
 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

Back to Microsoft SQL Server: Programming FAQ Index
Back to Microsoft SQL Server: Programming Forum
My FAQ Archive
Email This FAQ To A Friend

My Archive