【问题标题】:How to set optional field in where clause query?如何在 where 子句查询中设置可选字段?
【发布时间】:2018-09-30 05:46:51
【问题描述】:

我有 SQL 查询,在某些情况下我必须过滤位字段。如果参数等于一个空字符串,那么我不应该在我的过滤器中包含这个位字段。 SQL Server 2008 有什么好的方法吗? 示例如下:

<cfargument name="masterActive" type="string" required="yes" default="">

<cfquery name="getRecords" datasource="#dsnRead#">
    DECLARE @ActiveFlag bit;
    SET @ActiveFlag = <cfqueryparam value="#trim(arguments.masterActive)#" cfsqltype="cf_sql_bit">;

    SELECT tm_name, tm_comment, tm_active
    FROM Master WITH (NOLOCK)
    WHERE tm_tblid = <cfqueryparam value="#trim(arguments.masterTblid)#" cfsqltype="cf_sql_char" maxlength="15">
        AND tm_active = @ActiveFlag -- This field should be optional (if @ActiveFlag empty do not include tm_active in the filter)
</cfquery> 

【问题讨论】:

    标签: sql sql-server-2008 filter where


    【解决方案1】:

    代替

    AND tm_active = @ActiveFlag
    

    将以下内容添加到您的 where 子句中:

    AND (@ActiveFlag is null or tm_active = @ActiveFlag)
    

    但请注意,参数嗅探可能会导致未来的性能问题。 见here

    考虑添加这个

    AND (@ActiveFlag is null or tm_active = @ActiveFlag) 
    OPTION (OPTIMIZE FOR (@ActiveFlag UNKNOWN)) 
    

    【讨论】:

      猜你喜欢
      • 2012-05-05
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 2012-10-09
      • 2013-09-04
      • 2017-11-14
      • 1970-01-01
      • 2021-01-20
      相关资源
      最近更新 更多