Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
  • 한국 커뮤니티
0

Dynamic query, where clause help

Explorer ,
Aug 02, 2010 Aug 02, 2010

Hi Folks,

Using my code below to generate a query.

When using more than one condition, I'm not sure how to work out where the AND goes.

Can anyone please help?

Thankyou

WHERE
<cfif stafffilter neq "">
deviceofficer = #stafffilter#
</cfif>
<cfif assetid neq "">
AND deviceasset = '#assetid#'
</cfif>
<cfif isdefined("noasset")>
AND deviceasset = ''
</cfif>
  <cfif  isdefined("noserial")>
AND deviceserial = ''
</cfif>
<cfif serial neq "">
AND deviceserial = '#serial#'
</cfif>
<cfif servicearea neq "">
AND deviceservice = #servicearea#
</cfif>
ORDER by locationname

TOPICS
Database access
796
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Aug 02, 2010 Aug 02, 2010

where 1 = 1

if/else logic goes here.  Use "and" every time.

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Aug 02, 2010 Aug 02, 2010
LATEST

I do this sort of thing:

<cfset sWhereAnd = "WHERE">

<cfif isdefined("colFilter")>

     #sWhereAnd# col = #colFilter#

    <cfset sWhereAnd = "AND">

</cfif>

<cfif isdefined("someOtherColFilter")>

     #sWhereAnd# someOtherCol = #someOtherColFilter#

    <cfset sWhereAnd = "AND">

</cfif>

[etc]

(that's pseudocode... I'd never use isDefined() or not use a <cfqueryparam> tag for my parameter values).

I don't like doing the somewhat popular WHERE 1=1 approach as it can force a full table scan (all rows in the table will match that, and each WHERE filter expression is applied to every row of the table being filtered), unless the DB optimises it out as noise (which is what it is).  To me it's using bad SQL to cut corners.

To be honest though, I shy away from these generic sort of queries these days.  Most of the genericism never gets used, and more specific requirements are better implemented to meet the precise need.

--

Adam

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Resources