Search code examples
coldfusionscopeqoq

Var scoping issue possibly?


A few times in my functions I have stuff like this:

<cffunction name="mergeData">
<cfquery name="myQuery">
SELECT columnName FROM tableName
</cfquery>

<cfquery dbtype="query" name="myOtherQuery">
SELECT columnName FROM myQuery
</cfquery>
</cffunction>

<cfset resulta = mergeData(queryA) />
<cfset resultb = mergeData(queryB) />
<cfset resultc = mergeData(queryC) />

Occasionally then I get the error The select column reference [myQuery.columnname] is not found in table [myQuery].

So what could be causing this. How can I diagnose. I was thinking it could be a scoping issue, so I'm going to add <cfquery name="local.myQuery"> just to make sure things are contained in the function (I should be doing that anyway probably). But when something only happens sometimes I have a hard time figuring out how to diagnose.

EDIT: Added some clarity on why it's most likely a scoping issue. My thought is that myQuery is poossibly being referenced in other calls. I mean, it's not like it's running multiple threads on the data, but is it possible that that could be the cause? Are there other causes? This isn't always the case when I get the error. I also get it on a page where it function is only running once.


Solution

  • In the query of queries, use brackets around the local scope prefix.

    <cffunction name="mergeData">
        <cfquery name="local.myQuery">
            SELECT columnName FROM tableName
        </cfquery>
    
        <cfquery dbtype="query" name="local.myOtherQuery">
            SELECT columnName FROM [local].myQuery
        </cfquery>
    </cffunction>
    
    <cfset resulta = mergeData(queryA) />
    <cfset resultb = mergeData(queryB) />
    <cfset resultc = mergeData(queryC) />