Friday, September 24, 2004

ColdFusion QoQ Date Comparison

ColdFusion Query of Queries are a useful way of filtering an existing, in-memory recordset by executing a SQL query against the dataset.

Unfortunately, the documentation and more importantly, error handling for this otherwise cool ColdFusion feature are a bit lacking. Today I was trying to filter a query by date. The query had columns such as:

articleid,headline,author,publishdate

I needed to get the articles after a certain date and tried to do a simple QoQ:

<cfquery dbtype="query" name="filter">
select * from results WHERE publishdate > #startDate#
</cfquery>

This query returns an error about unsupport type comparision. After trying numerous functions and syntax changes, Ryan suggested I try CFQUERYPARAM, which (unexpectedly) worked perfectly:

<cfquery dbtype="query" name="filter">
select * from results
WHERE publishdate > <cfqueryparam value="#startDate#" cfsqltype="CF_SQL_DATE">
</cfquery>
This got me the exact results I needed. I'm still not exactly sure why the CFQUERYPARAM fixed the problem; my impression was that it was used for doing parameterized queries (prepared statements) against a SQL database, but in this case it appears to be setting some sort of data type flag internally that allows the comparison to work.

If you've been working with ColdFusion for a long time, you may be wondering why I just don't filter the original query (results) rather than use the slower QoQ functionality. In this case though, the query is not coming from a database and doesn't support date filtering - so QoQ is exactly the tool needed to do the filtering.

8 Comments:

At 1:29 PM , Blogger Ryan said...

Yeah, i'm big in Japan.

 
At 11:35 PM , Blogger Dave said...

Nice work. Wish Macromedia would include this example in their documentation.

David Levin

 
At 1:32 PM , Anonymous Anonymous said...

I try to do QoQ with verity search...

I can't get it...

what format has your startdate

made it with dateAdd

 
At 1:20 PM , Anonymous Tim said...

Wow... that was just the answer I was looking for. Thanks!

 
At 5:21 AM , Anonymous Anonymous said...

Thank you soo much. I spent an hour trying to figure this out and your comments saved the day. Most appreciated. It worked beautifully.

 
At 10:21 AM , Anonymous Anonymous said...

big THANKS!

 
At 7:35 AM , Blogger phenotypical said...

Well, this does get past the unsupported type comparison, but it still seems to evaluating the data as a string (and filtering alphabetically) and not as a date (and filtering chronologically). Ben Nadel (of course) shares the workaround: http://www.bennadel.com/blog/379-ColdFusion-Query-of-Queries-Unexpected-Data-Type-Conversion.htm

 
At 4:34 PM , Blogger Deepak Yadav said...

thanks a lot :)

 

Post a Comment

<< Home