【问题标题】:SQL - ignore where clause if null / no inputSQL - 如果 null / 没有输入,则忽略 where 子句
【发布时间】:2017-06-29 02:22:56
【问题描述】:

我正在构建一个 SSRS 报告,并希望我的参数之一在输入数据时是可选的。

这是一个示例查询,以便更好地理解:

SELECT
 C1
,C2
,C3
FROM
 db_Database..tb_Table
WHERE
 tb_Table_DateTime between [THEN] and [NOW]
 AND
 tb_Table_Integer IN (@Integer)

我正在尝试确定在我的查询中是否可以忽略整个问题:

AND tb_Table_Integer IN (@Integer)

用户选择不输入任何数字的行。

基本上,我希望返回所有数据,除非通过@integer 另有指定。

如果在查询中无法实现,是否可以在 Visual Studio 中实现?

干杯。

【问题讨论】:

    标签: sql sql-server-2008 ssrs-2008-r2


    【解决方案1】:

    这通常通过以下方式处理:

    WHERE . . . AND
          (@Integer IS NULL OR tb_Table_Integer = @Integer)
    

    不要使用IN (@Integer)。这有点暗示您认为@Integer 可能是一个列表。这是不可能的。

    【讨论】:

      【解决方案2】:

      最常用的方法是使用 coalesce 或 nullif。像这样:

      WHERE coalesce(@integer,tb_Table_Integer) = tb_Table_Integer
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-23
        • 1970-01-01
        • 2014-03-08
        • 2022-01-19
        • 1970-01-01
        • 2020-01-28
        • 1970-01-01
        • 2021-09-30
        相关资源
        最近更新 更多