Select random number of records


This tip shows how (from a single stored procedure) select X (parameter) number of random records.

Say we have the famous Northwind database, table Customers.

We want to create a stored procedure fetching @cnt number of random records- meanig we can call it like

ListRandomCustomers 12

to get 12 random records

ListRandomCustomers 5

to get 5 random records

etc.

The trick is to use set rowcount for limiting the resultset - and the trick to get random records is to oder by newid()



create proc ListRandomCustomers(@cnt int)
as
set rowcount @cnt
select * from customers
order by newid()
set rowcount 0