I've had the need to select a random record from a table within a ColdFusion app and I found two ways of doing this...
1. If using MS SQL Server, use the newID() function. MS SQL Server creates a guid for each row with each query that it uses internally to track the rows - independent of the primary key. Here is an example:
<cfquery name="query1" datasource="your_datasource">
SELECT TOP 1 *
FROM tbl_name
ORDER BY newID()
</cfquery>
2. Use ColdFusion to select a random record for you. In this process you use RandRange() to do the work for you. Here is an example:
<cfquery name="query1" datasource="your_datasource">
SELECT *
FROM tbl_name
</cfquery>
<cfset randomRow = RandRange(1,query1.RecordCount)>
Recent Comments