Tuesday, 12 June 2012

How do I randomly show a query record?

The easiest way to do this is by the "ORDER BY newid()" statement within your SQL statement. Drawback is that you need SQL server with this.

SELECT TOP 1 *
FROM table
ORDER BY newid()

The query above will give you a randomly choosen record each time.

Another way of doing this is by randomly displaying a record from the queryset you have.. you can do that like this (if you use access or some other database)

<cfquery name="rs" datasource="#dsn#">
  SELECT *
  FROM table
</cfquery>

<cfset displayRow = randRange(1,rs.recordcount)>
<cfoutput query="rs" startrow="#displayRow#" maxrows="1">
  -- show your record
</cfoutput>

No comments:

Post a Comment