【问题标题】:How can I filter by a subset of conditions based on a parameter in Microsoft SQL?如何根据 Microsoft SQL 中的参数按条件子集进行筛选?
【发布时间】:2017-12-09 20:08:15
【问题描述】:

我在 SQL 查询中有一个参数,我想在其中选择可能行的子集,或者根据参数选择一个。

基本上,我有一个名为 model 的列,它可以包含 1000、2000、3000、4000 或 5000。当参数设置为 NULL 时,我希望它只选择 1000、2000 和 3000,但不是 4000 或 5000。

我尝试过 CASE 语句的各种组合,即

WHERE model = CASE WHEN @model = NULL THEN model = 1000 OR model = 2000 OR 
model = 3000 ELSE @model END AND <query continues>

如何在 SQL Server 中实现这一点?

【问题讨论】:

  • 我想只是不要把它放在Where clause

标签: sql sql-server


【解决方案1】:

只需使用or

WHERE ( (@model is null and model in (1000, 2000, 3000)) or
        model = @model
      )

【讨论】:

    【解决方案2】:

    尝试以下方法之一:

    Where (model = @model OR 
    (@model IS NULL AND model <> model IN (1000,2000,3000,4000))
    

    Where (model = @model OR (@model IS NULL AND model <> model <> 5000)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-16
      • 1970-01-01
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多