Shaun Mccran

My digital playground
 
05
M
A
R
2010

Returning values from mySQL in a select query as Yes/No rather than 1/0

Whilst writing a ColdFusion based query to create a JSON response I thought I'd look up returning data values as a "Yes/No" string rather than "1/0". Then I wouldn't have to transform it in any way to use in the JSON build script.

The mySQL version allows you to do this by evaluating the value, and matching a string if the condition is met, like this:

view plain print about
1SQL version:
2SELECT intid,varuserfname,varusersname, IF(intactive<>0, "Yes", "No")
3FROM     table.users

This does not work in ColdFusion at all. An error is thrown:

After a little tweaking it seems that if you alias the field it does work. In the example code below I've simply aliased the field with its own name.

I'm not exactly clear why, as the error message above isn't all that helpful.

view plain print about
1CF version:
2SELECT intid,varuserfname,varusersname, IF(intactive<>0, 'Yes', 'No') as intactive
3FROM     table.users

TweetBacks
Comments
Ben Nadel's Gravatar I've seen that error many times before :) In my experience, any time I have an error that says "not indexable by", it means that I tried to access a column name that didn't exist (typically because I misspelled it). You probably tried to do:

#yourQuery.intactive#

... and the "intactive" column didn't exist. This would make sense in the first demo since you're not aliasing a column, but rather, creating a completely new, calculated column based on the intactive column. If you dump out the query result, it probably gave it some crazy column name.

For example, if I run the query:

select IF( id = 3, 'a', 'b' ) from blog_entry LIMIT 5

... the column name comes back as "IF( id = 3, 'a', 'b' )"... funky!

So anyway, that's why the aliasing is crucial.
# Posted By Ben Nadel | 3/12/10 10:25 PM

This content is purely my opinon, any offence or errors are unintentional, please comment your views appropriately
Site Credits
Aggregated by ColdfusionBloggers.org Powered by Coldfusion

Technology & Science Blogs - BlogCatalog Blog Directory Blog Directory & Search engine