【问题标题】:Where clause in SQL Query skip date filter when date is null当日期为空时,SQL Query 中的 Where 子句跳过日期过滤器
【发布时间】:2015-10-19 21:50:00
【问题描述】:

我的搜索查询的参数是名称、起始日期、截止日期。当我将空字符串或 null 传递给日期参数时,它应该只返回与名称匹配的所有数据。这段代码对我不起作用。

WHERE name=@name 
AND 
(CASE WHEN @_from IS not null 
            THEN
                Servicedate<=@_from 
            END)

这也不适合我。

WHERE name = @name AND
Servicedate>=ISNULL((case when @_from='' then NULL else @_from),Servicedate)

谢谢。

【问题讨论】:

  • 是mysql还是sql-server。这是两个非常不同的 DBMS。

标签: mysql sql sql-server sql-server-2008


【解决方案1】:
WHERE
(name=@name AND @_from IS NOT NULL AND @_from <> '' AND Servicedate<=@_from )
OR
(name=@name AND (@_from IS null or @_from = ''))

【讨论】:

    【解决方案2】:

    你可以用这个:

    WHERE
        name = @name
        AND (@_from IS NULL OR ServiceDate >= @_from)
        AND (@_to IS NULL OR ServiceDate <= @_to)
    

    如果未设置变量(@_from@_to),则条件将返回 true,因为 @var IS NULLtrue

    【讨论】:

      【解决方案3】:
      WHERE ( name=@name AND @_from IS NOT NULL AND Servicedate<=@_from )
            OR
            ( name=@name AND @_from IS null )
      

      如果日期参数@_from 为空,则仅在名称参数@name 上进行搜索,否则ServiceDate 列与日期参数@_from 匹配

      【讨论】:

        猜你喜欢
        • 2017-06-05
        • 2022-05-05
        • 1970-01-01
        • 2010-12-12
        • 2018-11-03
        • 2013-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多