Random tuples from Sql Server 2005 or greater

We sometime need to show random items from our databases on users screen. Random photos of the week, random sayings and so many situations the pages look so good when there is a bunch of sticks with variety.
This is nice but real good headache to solve when we have a huge list of items in the database, because randomizing at the program level using a huge list not a good idea having overhead to the memory.
Simple sql will solve the issue like this
SELECT TOP 10 * FROM tbl_items ORDER BY NewID()
Filters out tem items randomly from table tbl_items.
If you use Linq to sql as your query provider
You have to use a partial class for your data context class and introduce a method to get a new Guid as follows
Let DBContext be your datacontext class,
Then create a new class
public partial class DBContext
{
     public Guid NewID()
     {
         return Guid.NewGuid();
     }

}
In your linq query
var randList = from i from tbl_items 
                    orderby NewID()
                    select i;
return randList.Take(10);
No more random headaches ……………

Comments

Popular posts from this blog

Log4Net Different files in the same assembly

ටෙස්ලා

Setup Test automation with Selenium and Ruby