带AND的SQL Server OR语句

时间:2013-09-13 09:48:28

标签: sql sql-server tsql

我有这样的查询

select * 
from MyTable
where (@Param is null or (FieldCode = 'Whatever' and FieldValue like '%' + @Param + '%'))

当我在where子句中添加更多语句时,我的查询速度变慢了。我认为这是因为它在OR之前评估AND部分(包含LIKE,它可能很慢)。如果@Param为null,我希望它跳过AND的查询,我应该怎么做?

3 个答案:

答案 0 :(得分:0)

我强烈建议你查看你肯定遗失的索引。 除此之外你真的需要使用每一列吗?使用(NOLOCK)读取数据。 此外,对于索引非常糟糕,看看你是否真的需要你的程序的第一个%,或者你是否可以在客户端搜索数据(过滤更大的数据子集)

答案 1 :(得分:0)

如果@param为null,你总是可以将它分开并只做一个不同的select语句。

If @Param is not null
    select * 
    from MyTable
    where (FieldCode = 'Whatever' and FieldValue like '%' + @Param + '%')
Else
    select *
    from MyTable

答案 2 :(得分:-1)

尝试以获得更好的性能:

select * 
from MyTable
where @Param is null or case when @Param is not null and FieldCode = 'Whatever' 
then case when FieldValue like '%' + @Param + '%' then 1 end end = 1

这样可以防止在没有必要时进行繁重的野生比较