当bit = 1时,只使用where子句

时间:2017-03-28 01:20:09

标签: sql sql-server tsql

我现在有一些看起来像这样的SQL代码。

    insert into @SortedProducts (peid)
    select pd.ProductEntryId 
    from @ProductFilters FILT
        INNER JOIN J_ProductDetails pd ON FILT.ProductEntryId = pd.ProductEntryId
    WHERE pd.Active = 'True'
    and pd.IsRangeOfProducts = CASE WHEN @ClearanceFeatureApplied = 1 then 0 else 1 END 

但是,在最后一行,我只想在@ClearanceFeatureApplied = 1的情况下应用where子句

如果@ClearanceFeatureApplied = 0,那么我不应该有这个where子句。 pd.IsRangeOfProducts也有点。

非常感谢任何建议。

谢谢!

3 个答案:

答案 0 :(得分:6)

只需使用布尔逻辑:

insert into @SortedProducts (peid)
    select pd.ProductEntryId 
    from @ProductFilters FILT join
         J_ProductDetails pd 
         on FILT.ProductEntryId = pd.ProductEntryId
    where pd.Active = 'True' and
          (@ClearanceFeatureApplied <> 1  or pd.IsRangeOfProducts = 0) ;

答案 1 :(得分:2)

当@ClearanceFeatureApplied = 0时,您可以在where子句(括号括起来)中添加OR以忽略此部分:

insert into @SortedProducts (peid)
select pd.ProductEntryId 
from @ProductFilters FILT
    INNER JOIN J_ProductDetails pd ON FILT.ProductEntryId = pd.ProductEntryId
WHERE pd.Active = 'True'
and (@ClearanceFeatureApplied = 0 OR pd.IsRangeOfProducts = CASE WHEN @ClearanceFeatureApplied = 1 then 0 else 1 END)

如果位列中有空值,则需要为此进行编译。

答案 2 :(得分:0)

如果我理解正确,那么可能是这样的:

WHERE pd.Active = 'True'
    and 1 = CASE WHEN @ClearanceFeatureApplied = 0 THEN 1 
                 WHEN pd.IsRangeOfProducts = 0 THEN 1  -- XX
                 ELSE 0 END

以上假设@ClearanceFeatureApplied不会为null。 如果你到达第XX行,那么@ClearanceFeatureApplied将始终为1, 所以我优化了条件:

 and pd.IsRangeOfProducts = CASE WHEN @ClearanceFeatureApplied = 1 then 0 else 1 END 

到:

  pd.IsRangeOfProducts = 0