INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS
Come Join Us!
Are you a
Computer / IT professional?
Join Tek-Tips now!
- Talk With Other Members
- Be Notified Of Responses
To Your Posts
- Keyword Search
- One-Click Access To Your
- 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.
Partner With Us!
"Best Of Breed" Forums Add Stickiness To Your Site
(Download This Button Today!)
"...I just wanted to say how much I have enjoyed these forums. I am a new user and have a lot of elementary questions. I get quick answers with a friendly attitude..."
Where in the world do Tek-Tips members come from?
How Can I Select Random Records From a Table with T-SQL?
Posted: 3 Oct 01 (Edited 6 Jun 03)
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.
--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
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
--Loop and slect records
--Generate a random number
SET @rndno=@count * RAND() + 1
--Insert record if not already on table
Insert #r (EmpID)
Select EmpID From #t
And Not Exists (Select * From #r Where EmpID=#t.EmpID)
--Decrement counter if record was inserted
If @@rowcount>0 SET @recno=@recno-1
--Return result set containing the selected records
FROM Employees e Inner Join #r
ON e.EmpID = #r.EmpID
Drop table #r
Drop table #t
Back to Microsoft SQL Server: Programming FAQ Index
Back to Microsoft SQL Server: Programming Forum
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:
- Talk To Other Members
- Notification Of Responses To Questions
- Favorite Forums One Click Access
- Keyword Search Of All Posts, And More...
Register now while it's still free!
Already a member? Close this window and log in.
Join Us Close