当日期为空时,SQL 查询中的Where子句跳过日期过滤器

Ceg*_*one 1 mysql sql sql-server sql-server-2008

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

WHERE name=@name 
AND 
(CASE WHEN @_from IS not null 
            THEN
                Servicedate<=@_from 
            END)
Run Code Online (Sandbox Code Playgroud)

这也不适合我。

WHERE name = @name AND
Servicedate>=ISNULL((case when @_from='' then NULL else @_from),Servicedate)
Run Code Online (Sandbox Code Playgroud)

谢谢。

Fel*_*tan 5

你可以使用这个:

WHERE
    name = @name
    AND (@_from IS NULL OR ServiceDate >= @_from)
    AND (@_to IS NULL OR ServiceDate <= @_to)
Run Code Online (Sandbox Code Playgroud)

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