在 SQL 中自定义 where 子句条件

Customize where clause condition in SQL

我需要根据来自 HTML 表单的输入自定义 where 子句。例如,如果用户没有填充就绪字段。我希望 select 查询到 return 项,这些项对就绪字段具有任何值,包括空值,否则 return 与用户输入的值匹配。

declare @name varchar(max) = '%%'

declare @state  varchar(max) = '%%'

declare @ready  varchar(max) = '%%'

select *

from DummyTable

where   ([name] like  @name ) and 

        ([state] like @state ) AND 

        ([ready] LIKE @ready OR [ready] = case when @ready = '' then null else '' end  )  

我猜你正在寻找这样的东西:

where   ([name] like  @name OR @name is NULL) and 

        ([state] like @state OR @state is NULL ) AND 

        ([ready] LIKE @ready OR @ready is NULL)  

因此,如果没有输入任何值,则无需过滤此字段