Search code examples
sqlcoldfusioncfquery

Why does adding "AND 1=1" fix SQL query in Coldfusion?


There have been several times when I've created a cfquery and for no good reason, it doesn't work. For example, I recently had a query like this:

<cfquery name="get_projects" datasource="#application.dsn#">
        SELECT *
        FROM   projects
        WHERE  project_id = <cfqueryparam cfsqltype="cf_sql_integer" value="#project_id#">

          <cfif start_date NEQ "">
               AND project_start_date = <cfqueryparam cfsqltype="cf_sql_timestamp" value="#start_date#">
          </cfif>

        ORDER BY project_name
    </cfquery>

I confirmed the start_date variable was an empty string. However, I'll get an error that points to that line and says "Value can not be converted to requested type" even though it should never have gotten to that line.

But here's the really weird thing.... If I add "AND 1=1" to the WHERE clause, the query works perfectly.

I've had this happen sporadically on a number of queries, but I can't say I recognize a pattern to it. Always the query is written perfectly. In some cases, the query was working previously, and suddenly it stops, possibly when there is a change somewhere else in the file. All I have to do is add "AND 1=1" to the WHERE clause, and it works again. Anyone else run into this or have ideas how to fix it?


Solution

  • I've seen it happen where the query gets compiled incorrectly and changing any part of the text in it (such as adding 1=1) re-compiles it.