Quick Tip - Treating a ColdFusion Query like a Structure

This post is more than 2 years old.

I've mentioned this before, but as it came across today on my forums, I thought it wouldn't hurt to write up a quick example. ColdFusion queries are pretty easy to work with. You have multiple options for looping over them and can easily address the data when using a cfoutput:

<cfoutput query="getArt"> Art: #artname#<br/> </cfoutput>

Outputting a query is probably one of the first things we do as ColdFusion developers. The user on my forums though had a problem where he didn't know the exact name of the column. He knew it would begin with "b" and the rest of the column would be based on some other variable.

ColdFusion allows us to treat a query like a structure of arrays. By that I mean you can address a column using structure notation and you get a particular row by using array notation.

So given that the column is "b"+groupid, and given that you are inside a query driven cfoutput, you can use this syntax:

<cfoutput query="getStuff"> #getStuff["b#groupid#"][currentRow]# </cfoutput>

currentRow is simply one of those built in variables you have when working with a query.

The only real caveat to this valueList function. It requires a hard coded query and column name. If you wanted to use valueList with the dynamic column above, you would need to use evaluate (which, remember, isn't the end of the world like it used to be):

<cfset list = evaluate("valueList(getStuff.b#groupid#)")>
Raymond Camden's Picture

About Raymond Camden

Raymond is a senior developer evangelist for Adobe. He focuses on document services, JavaScript, and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Archived Comments

Comment 1 by David Mineer posted on 11/26/2009 at 12:13 AM

Looks like there is a # missing in:


Comment 2 by Raymond Camden posted on 11/26/2009 at 12:20 AM

Fixed, thanks.

Comment 3 by salvatore fusto posted on 11/26/2009 at 12:56 PM

also, a final ) is missing in
<cfset list = evaluate("valueList(getStuff.b#groupid#)">

Comment 4 by Raymond Camden posted on 11/26/2009 at 5:07 PM

Doh! Thanks. Fixed.

Comment 5 by Grant Copley posted on 11/26/2009 at 6:23 PM

11 years of CF programming and still everyday I'm learning little nuggets I love about this language! Happy Thanksgiving everyone.

Comment 6 by Lola LB posted on 11/26/2009 at 7:13 PM

I'm thankful that you're around to explain stuff like this in clear, simple language!