Looping Over a Query

Description

A loop over a query repeats for every record in the query record set. The cfloop results are just like a cfoutput. During each iteration of the loop, the columns of the current row are available for output. The cfloop tag lets you loop over tags that can not be used inside cfoutput.

Category

Flow-control tags

Syntax

<cfloop query = "query_name"
  startRow = "row_num"
  endRow = "row_num"> 

See also

cfabort, cfbreak, cfexecute, cfexit, cfif    cfelseif    cfelse, cflocation, cfswitch    cfcase    cfdefaultcase, cfthrow, cftry cfcatch

Attributes

Attribute
Description
query
Required. Specifies the query that controls the loop.
startRow
Optional. Specifies the first row of the query that is included in the loop.
endRow
Optional. Specifies the last row of the query that is included in the loop.

Example 1

The following example shows a cfloop looping over a query that works in the same way as a cfoutput tag that uses the query attribute:

<cfquery name = "MessageRecords" 
  dataSource = "cfsnippets"> 
  SELECT * FROM Messages 
  </cfquery> 

<cfloop query = "MessageRecords"> 
  <cfoutput>#Message_ID#</cfoutput><BR> 
</cfloop>

Example 2

The cfloop tag also provides iteration over a recordset with dynamic start and stop points. This mechanism provides a simple means to get the next n sets of records from a query.

The following example loops from the tenth through the twentieth record returned by "MyQuery ":

<cfset Start = 10> 
<cfset End = 20> 

<cfloop query = "MyQuery" 
  startRow = "#Start#" 
  endRow = "#End#"> 
  <cfoutput>#MyQuery.MyColName#</cfoutput><BR>
</cfloop>

The loop stops when there are no more records or when the current record index is greater than the value of the endRow attribute.

Example 3

The advantage of looping over a query is that you can use CFML tags that are not allowed in a cfoutput. The following example combines the pages that are returned by a query of a list of page names into one document, using the cfinclude tag.

<cfquery name = "GetTemplate" 
  dataSource = "Library"
  maxRows = "5"> 
  SELECT TemplateName FROM Templates 
</cfquery> 

<cfloop query = "TemplateName"> 
  <cfinclude template = "#TemplateName#"> 
</cfloop>