Return a CFQuery from CFFunction

Coldfusion is old but not dead yet, so it is not surprise if you still need to work on them from time to time. I recently changed my job and encountered some web apps coded with ColdFusion.

Today I need to put a cfquery into a function so the query can be reused. Here is the solution I came up with.

<cffunction name="myQuery" access="private">
 <cfargument name="condition" required="yes" type="string">
 <cfquery name="expiryQuery" datasource="myDb">
 select count(id) AS expired
 from myTable
 where expiryDate<= getDate()  and #arguments.condition# 
 <cfreturn myQuery>

Please note that the code above is for demonstration purpose. To prevent SQL injection attack, you need to use cfqueryparam to qualify the query parameters.

Now you can invoke the function and assign the query result to a variable for later access

<cfset result1=#expiryCheck("flag = 1")# >

<cfset result2=#expiryCheck("flag = 2")# >
This entry was posted in Coldfusion, Programming and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s