Ask Ben: Testing The Existence Of A Query Column In CFScript

Posted October 2, 2006 at 4:36 PM

Tags: Ask Ben, ColdFusion

When I am in a script block, how can I test for the existence of a column?

Testing for existence of column in a query (I assume you mean a query column) is easy inside of a CFScript block in ColdFusion. Actually, it's easy anywhere: all you have to do is check to see if it is in the ColdFusion query's ColumnList attribute:

 Launch code in new window » Download code as text file »

  • <!--- Check to see if column exists. --->
  • <cfif ListFindNoCase( qQueryObject.ColumnList, "column_name" )>
  •  
  • <!--- Column found! --->
  • Sweeet! #column_name# is available in the query.
  •  
  • </cfif>

This uses searches through the column list of the query. I am never sure what case this list comes back in (upper, lower, mixed) and so I do a NoCase find method call. This should return the index of the matching item. If there is no matching item, then it returns zero which ColdFusion will interpret as False.

You can also reference a ColdFusion query object like it was a struct with keys. These keys, among other things, contain the columns. Therefore, you can also check for key existence:

 Launch code in new window » Download code as text file »

  • <!--- Check to see if column KEY exists. --->
  • <cfif StructKeyExists( qQueryObject, "column_name" )>
  •  
  • <!--- Column found! --->
  • Sweeet! #column_name# is available in the query.
  •  
  • </cfif>

Now, you asked about doing this inside of ColdFusion CFScript tags. These are just simple list and key checking operations and can be easily translated to CFScript:

 Launch code in new window » Download code as text file »

  • // Check to see if column exists.
  • if (ListFindNoCase( qQueryObject.ColumnList, "column_name" )){
  •  
  • // Column found!
  • WriteOutput(
  • "Sweeet! #column_name# is available in the query."
  • );
  •  
  • }
  •  
  •  
  • // Check to see if column KEY exists.
  • if (StructKeyExists( qQueryObject, "column_name" )){
  •  
  • // Column found!
  • WriteOutput(
  • "Sweeet! #column_name# is available in the query."
  • );
  •  
  • }

You would of course replace qQueryObject with name of your query and column_name with the name of your query. Good luck!

Download Code Snippet ZIP File

Comments (0)  |  Post Comment  |  Ask Ben  |  Permalink  |  Other Searches  |  Print Page



Adobe ColdFusion 8.0.1 Update - Helping Programmers To Be Signifanctly Less Girlie - Download ColdFusion 8 Update 8.0.1 Now.

Reader Comments

There are no comments posted for this web log entry.


Post Comment  |  Ask Ben


Home   |   Web Log   |   ColdFusion   |   Projects   |   Resume   |   Job Form   |   Search   |   Contact
Epicenter Consulting - Custom Software Solutions for Business Evolution HostMySite.com - The Leader In ColdFusion Hosting