如何在where子句查询中设置可选字段?

时间:2018-04-19 16:22:32

标签: sql sql-server-2008 filter where

我有SQL查询,在某些情况下我必须在位字段上进行过滤。如果参数等于空字符串,那么我不应该在我的过滤器中包含此位字段。有没有一种goo方式来使用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> 

1 个答案:

答案 0 :(得分:0)

而不是

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))