My Account   Contact Us    
  
» HomeProductsSupportDeveloper CommunityCompany
Selecting Random Rows From a Database
Author: Pete Freitag
Category: ColdFusion
Display random data with coldfusion, by caching the data in the application scope.

<cfset refresh = 0>
<cfset randomContent = "">
<cflock type="readonly" scope="application" timeout="30">
  <cfif NOT IsDefined("application.items")>
    <cfset refresh = 1>
  <cfelse>
    <cfset rand = RandRange(1, ArrayLen(application.items)>
    <cfset randomContent = application.items[rand]>
  </cfif>
</cflock>

<cfif refresh>
  <cfquery name="q">
    SELECT item FROM table
  </cfquery>

  <cflock scope="application" type="exclusive" timeout="30">
    <cfset application.items = ArrayNew(1)>
    <cfoutput query="q">
      <cfset application.items[q.CurrentRow] = q.item>
    </cfoutput>

    <cfset rand = RandRange(1, ArrayLen(application.items)>
    <cfset randomContent = application.items[rand]>
  </cflock>
</cfif>

This does require that all the data is stored in server memory, if you are displaying a different result in each page request it is worth it, because your saving a lot of db access.

Another technique is to use a stored procedure, this article has a good stored proc to use on Microsoft SQL Server http://www.aspalliance.com/stevesmith/articles/randomselect.asp



Content Management Powered by ActivEdit  ActivEdit Browser Based WYSIWYG HTML Editor

More Code Samples

Sign up for our newsletter: | Subscribe with RSS: RSS
© ActivSoftware 1999 to 2005 | Privacy Statement