Coldfusion Query with index

I would love to be proved wrong by one of the ColdFusion gurus, but I had a real problem with this earlier today. Basically I needed to loop through a query, but I wanted to stop just before the last iteration. I wanted to write a dynamic SQL statement that stopped adding ‘AND’ before the last step. Here’s what I came up with

<cffunction name="blah"><cfset index = 0>

<cfquery name="query1" datasource="datasource">

select id

from table

</cfquery>

<cfquery name="query2" datasource="datasource">

select id2

from table2

where <cfloop query="query1">

id != #query1.ID#

 <cfset index = index +1>

<cfif index neq query1.recordCount>

AND

</cfif>

</cfloop>

</cfquery>

</cffunction>

This little bit of code adds ‘AND’ after ever iteration of the loop except the last. I’m sure there’s either a better way to do this, or that this is obvious, but hey – it worked!

Tags »

Author:admin
Date: Wednesday, 28. November 2007 0:07
Trackback: Trackback-URL Category: Coldfusion Codesnips

Feed for the post RSS 2.0 Comment this post

Submit comment