Santry Technology Solutions, Content Management, DotNetNuke, SharePoint Consulting
Register | Login
Wednesday, January 07, 2009

Sections
  
About Us
  
Partners
Downloads
  
 WWWCoder.com Resource Directory

Randomize a Resultset in SQL
3/22/2005 2:53:02 PM

In this article we provide a small code snippet on how to return records from a table in SQL in a random order.

In the following code snippet we show you how to randomize the result set on the SQL Server. In many cases you may wish to randomly return a set records. For example, in one application we wanted to return five records, but have them returned in a random pattern for a banner ad application on a Website.

Since the database could potentially contain many records than just five, we needed a way to even out the impressions that would be displayed on the site.

CREATE PROCEDURE dbo.GetRandomAds
-- outputs random top ads
(
)
AS
SELECT Top 5 Ads.* FROM Ads ORDER By NewId()
RETURN
GO

The random sort is being provided by adding the NewId() directive to the end of the TSQL statement. This enables us to pull five records out a time from the Ads table in a random order.

For small applications like this banner ad manager where the amount of records are not extremely high this solution would be viable.


Page Options:
format for printing  Format for Printer
email article  Email Page
add to your favorites   Add to Favorites
How would you rate the quality of this content?
Poor - - Excellent
Comments?
Overall Rating:
Comments Left:
Left on 8/20/2008 3:28:55 PM by Anonymous
Comments:
  

 Latest Articles
  

 Latest News
  

 

Spotlight
Syndication

 


 


Digg This
 


DotNetNuke Platinum Benefactor

  
 

 Terms Of Use | Privacy Statement
 Copyright 2008 - Santry Technology Solutions, Box 172, Girard, PA 16417, (814) 774-0970