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 Select Random Records From a Table with T-SQL?

Random Numbers

How Can I Select Random Records From a Table with T-SQL?

by  tlbroadbent  Posted    (Edited  )
/*
This T-SQL script demonstrates one method for selecting random records from a table. The example uses an employees table. However, It could be used to select from any table with a unique identifier or primary key column.

Created by Terry L. Broadbent, Oct 3 2001

Please inform me of any bugs encountered. Comments and suggestions for improvement are encouraged.
*/
[tt]
--Stop display of "row(s) affected messages
Set nocount on

--Create temporary table with identity column
Create table #t (EmpID char(6), RecID int identity(1,1))

--Create temporary table to hold randomly selected identifiers
Create table #r (EmpID char(6) constraint lnu unique)

--Select records from table into 1st temp table
Insert #t (EmpID)
Select EmpID From Employees
Where Status=1
Order By EmpID

--Declare variables needed for looping and counting
DECLARE @count int, @recno int, @rndno int
SELECT @count=COUNT(*) FROM #t

--Determine number of records to select
SET @recno=50

--Loop and slect records
While @recno>0
Begin

--Generate a random number
SET @rndno=@count * RAND() + 1

--Insert record if not already on table
Insert #r (EmpID)
Select EmpID From #t
Where RecID=@rndno
And Not Exists (Select * From #r Where EmpID=#t.EmpID)

--Decrement counter if record was inserted
If @@rowcount>0 SET @recno=@recno-1
End

--Return result set containing the selected records
SELECT e.*
FROM Employees e Inner Join #r
ON e.EmpID = #r.EmpID

--Cleanup
Drop table #r
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