Greg's Blog

helping me remember what I figure out

Outputting Queries With CFScript

| Comments

Over the past few months I have using more and more of CFScript to do my development. One of the things that still bothered me though was that I had not figured out how to loop over a result set. That no longer is the case… by using a combination of a CFC to execute the query and storing the result in a variable I was able to loop over this result set and grab the records and values in question.

As a base I used a CFC that executed the query and made a note of the column names that I wanted to work with. The format for accessing a record when using CFScript is: queryName[‘column name’][record]. A thing ot note is you can still access to the default variables that the query object generated.

For starters I made use of the recordcount variable to determine the number of loops that need to be executed. The loop takes the shape of a for loop.

<cfscript>
//invoke the object
yourCFC = CreateObject(“pathToCfc/cfcName”);
// execute the query by calling the method that holds the query
myQuery = yourCFC.fnYourMethod();
attributes.totalRecord = myQuery.recordcount;
if (attributes.totalRecord neq 0) { // check that a result was returned
// loop over the query
for (i=1; i lte attributes.totalRecord; i=i+1) {
// output the value for column: columnName
writeoutput(myQuery.currentrow & “. Column name has a value of: ” & myQuery[‘columnName’][i] & “<br />”);
}
} else {
writeoutput(“<p>Sorry no result.</p>”);
}
</cfscript>

It is pretty straight forward you just have to know how. Since you also have access to the query object variables columnList, I suppose you could stores these in a list and loop over that for each value of i as well.