Random Record in .NET

  • Thread starter Thread starter D. Shane Fowlkes
  • Start date Start date
D

D. Shane Fowlkes

I'm surprised I haven't found a clip of code or a tutorial on this.....I've
thumbed through a couple of books, did some Google searching for about 15
minutes and still no luck. =(

I'm simply trying to extract a random record from a table everything a page
loads. Does anyone have a clip of code or something I can use as a
reference. I can easily create a random number and I can easily create a
recordset...err...DataReader...but I'm having trouble connecting the dots.

TIA!

-Shane
 
int randomNumber = (generate a random number here)
sql = "SELECT * FROM
WHERE ID=' " + randomNumber + " ' "
 
If you are using SQL Server , this bit of T-SQL will return a random record.

Select top 1
newid() id, col,col2
from
my table
order by
id

A
 
Andrew, could you explain what this is doing please? I would be interested
to know how this works as it may come in handy for a project I have in mind.
 
Ok here's what's happening.
newid() generates a globally unique ID.
So each row in the select has this unique ID added to it as if it was part
of the table.
Now because we are sorting by newid() ,which is unique, we are in fact
retrieving a random row.

Regards, Andrew
 
Yes that's right but I wanted Shane to see what was happening ie. the
newid() being displayed.

A
 
Back
Top