User Guide

236 Chapter 2: ColdFusion Tags
cfloop: looping over a query
Description
A loop over a query executes for each record in a query record set. The results are similar to those
of the
cfoutput tag. During each iteration, the columns of the current row are available for
output. The
cfloop tag loops over tags that cannot be used within a cfoutput tag.
Syntax
<cfloop
query = "query_name"
startRow = "row_num"
endRow = "row_num">
</cfloop>
See also
cfabort, cfbreak, cfexecute, cfexit, cfif, cflocation, cfoutput, cfswitch,
cfthrow, cftry
Attributes
Example
This example shows a cfloop looping over a query 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>
The cfloop tag also iterates over a record set with dynamic start and stop points. This gets the
next n sets of records from a query. This example loops from the 10th through the 20th 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.
The advantage of looping over a query is that you can use CFML tags that are not allowed in a
cfoutput tag. 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"
Attribute Req/Opt Default Description
query Required Query that controls the loop.
startRow Optional First row of query that is included in the loop.
endRow Optional Last row of query that is included in the loop.