过滤条件只有一种

时间:2019-04-04 19:57:18

标签: sql tsql

我在WHERE子句中有一个验证,例如:

                         ...
                         AND (@BDOnly = 0
                             OR [DT].[Abbreviation] = @IsBDChecked)
                         AND (@CDOnly = 0
                             OR [DT].[Abbreviation] = @IsCDChecked)
                         AND (@PPOOnly = 0
                             OR [DT].[Abbreviation] = @IsPPOChecked)
                         AND (@FBOMOnly = 0
                             OR [DT].[Abbreviation] = @IsFBOMChecked)
                         AND (@APOnly = 0
                             OR [DT].[Abbreviation] = @IsAPChecked)
                         AND (@COOnly = 0
                             OR [DT].[Abbreviation] = @IsCOChecked)

因此,每个AND子句都会检查布尔值是0还是1,如果是0则只做任何事情,如果是1则做一个过滤器。我的问题是 如果我要发送两个值为1的邮件,则是

@BDOnly = 1@CDOnly = 1仅过滤其中之一,而是得到两个过滤器,我的意思是:

[DT].[Abbreviation] = @IsBDChecked

 [DT].[Abbreviation] = @IsCDChecked

我在做什么错?问候

1 个答案:

答案 0 :(得分:1)

我要在这里做个猜测,因为没有足够的数据。如果仅在设置Abbreviation时返回@IsBDChecked匹配@BDOnly的行,而在{{1}时返回Abbreviation匹配@IsCDChecked的另一行},请尝试以下操作:

@CDOnly

典型案例:

                        (@BDOnly = 1
                         AND [DT].[Abbreviation] = @IsBDChecked)
                     OR (@CDOnly = 1
                         AND [DT].[Abbreviation] = @IsCDChecked)
                     OR (@PPOOnly = 1
                         AND [DT].[Abbreviation] = @IsPPOChecked)
                     OR (@FBOMOnly = 1
                         AND [DT].[Abbreviation] = @IsFBOMChecked)
                     OR (@APOnly = 1
                         AND [DT].[Abbreviation] = @IsAPChecked)
                     OR (@COOnly = 1
                         AND [DT].[Abbreviation] = @IsCOChecked)

收益:

DECLARE @ADOnly BIT = 0
      , @BDOnly BIT = 1
      , @CDOnly BIT = 1
      , @IsADChecked NVARCHAR(100) = 'A'
      , @IsCDChecked NVARCHAR(100) = 'C'
      , @IsBDChecked NVARCHAR(100) = 'B'



;WITH myTable AS 
(
    SELECT * FROM (VALUES ('A'), ('B'), ('C')) X(Abbreviation)
)
SELECT *
  FROM myTable
 WHERE (@ADOnly = 1 AND Abbreviation = @IsADChecked)
    OR (@BDOnly = 1 AND Abbreviation = @IsBDChecked)
    OR (@CDOnly = 1 AND Abbreviation = @IsCDChecked)