Regual
Regual

Reputation: 377

Using StructKeyExists in place of IsDefined

For code enhancement purposes, we are going to convert all isDefined() calls to structKeyExists(). A couple of things that I need to know are:

How do we define a query in structKeyExists()? For instance:

<cfquery name="getname" datasource="dsn">select * from table</cfquery>

<cfif isDefined('getname') and getname.recordcount neq "">Do this</cfif>

Since there is no scope defined for isDefined(), what scope should we use for structkeyExists()?

Upvotes: 7

Views: 2147

Answers (2)

Frank Tudor
Frank Tudor

Reputation: 4504

This is an older question but for posterity.

<cfquery name="getname" datasource="dsn">
    select * from table
</cfquery>

<cfif getname.recordcount>Do this</cfif>

The cfif getname.recordcount works as Boolean check. If the result set brings nothing it fails...if it brings back a record than it satisfies the Boolean check.

To expand. Lets say we are selecting a specific field like id and we want to provide output for either condition:

It would look like this:

<cfquery name="getname" datasource="dsn">
    select id from table
</cfquery>


<cfif getname.recordcount>
    <cfoutput query="getname">
    #id#<br>
    </cfoutput>
<cfelse>    
    No records found.    
</cfif>

Upvotes: 0

barnyr
barnyr

Reputation: 5678

The default scope is variables, so StructKeyExists(variables,"getname") will perform your check for you.

However, unless there's missing logic in the example above, you don't need the isDefined/StructKeyExists check, because if you run a query, it'll always be defined, just with no rows present, so your second check on getname.recordcount should be sufficient.

Upvotes: 13

Related Questions