在SQL中自定义where子句条件

时间:2017-05-30 02:22:52

标签: sql sql-server where where-clause

我需要根据HTML表单的输入自定义where子句。例如,如果用户没有填充就绪字段。我希望select查询返回具有ready字段的任何值的项目,包括null,否则返回用户输入的值的匹配项。

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  )  

1 个答案:

答案 0 :(得分:1)

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

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

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

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

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

相关问题