<CFLOOP QUERY="query_name"
    STARTROW="row_num"
    ENDROW="row_num">

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 will be available for output. CFLOOP allows you to loop over tags that can not be used inside CFOUTPUT.

QUERY

Required. Specifies the query that will control the loop.

STARTROW

Optional. Specifies the first row of the query that will be included in the loop.

ENDROW

Optional. Specifies the last row of the query that will be included in the loop.

Examples

Example 1

The following example shows a CFLOOP looping over a query that works in the same way as a CFOUTPUT tag using the QUERY attribute:

<CFQUERY NAME="MessageRecords" 
    DATASOURCE="cfsnippets"> 
    SELECT * FROM Messages 
</CFQUERY> 

<CFLOOP QUERY="MessageRecords"> 
    <CFOUTPUT>#Message_ID#</CFOUTPUT><BR> 
</CFLOOP>

Example 2

CFLOOP also provides iteration over a recordset with dynamic starting and stopping points. Thus you can begin at the tenth row in a query and end at the twentieth. 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 is done when there are no more records or when the current record 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 returned by a query of a list of page names into a single document using the CFINCLUDE tag.

<CFQUERY NAME="GetTemplate" 
    DATASOURCE="Library"
    MAXROWS="5"> 
    SELECT TemplateName FROM Templates 
</CFQUERY> 
 
<CFLOOP QUERY="TemplateName"> 
    <CFINCLUDE TEMPLATE="#TemplateName#"> 
</CFLOOP>