April 10, 2007

cfquery 'result' attribute caveat

A great feature of which was introduced in CFMX7 is the addition of the ‘result’ attribute. When used, a developer can access a Structure of query result variables including the following keys:

  • Cache
  • ColumnList
  • ExecutionTime
  • RecordCount
  • SQL
  • SQLParameters

You can read more about the ‘result’ attribute in a previous post or at Live docs.

One thing I’ve come across is that the structure returned (by using the result attribute) is created where the query is executed and the value of ‘result’ references this struct in the local variable scope.

So an inline query followed by a reference to the ‘result’ struct would run fine:

<cfquery name="qData" dsn="myDSN" result="stResult">
	SELECT	*
	FROM	MyTable
</cfquery>

<cfoutput>
	#stResult.sql#
</cfoutput>

But a problem exists when you have a query in a Component that is being returned by a method call. In this case the structure won’t exist in the calling templates ‘local’ scope and an exception will be thrown.

stResult exception

The simple way around this is to declare the ‘result’ attribute in the request scope:

<cfquery name="qData" dsn="myDSN" result="request.stResult">
	SELECT	*
	FROM	MyTable
</cfquery>

Now you can reference the structure inside the calling template using the request scope:

<cfoutput>
	#request.stResult.sql#
	#request.stResult.cached
	etc
</cfoutput>

© Michael Sharman 2017