select top 20 id
from Employee e
where e.state=IsNull(@State,e.state)
and e.industry=IsNull(@Industry,e.Industry)
答案 0 :(得分:1)
我在这里看到的两个问题是在ISNULL()
子句中使用WHERE
函数并在WHERE
条件中使用参数,这使得很难确定是否使用索引查找。
根据我的观察,您可以将WHERE
条件更改为
where e.state is null or e.state = @State
and e.industry is null or e.Industry = @Industry
(或)尝试使用动态查询,而不是像
declare @sql varchar(200);
declare @cond varchar(100);
set @sql = 'select top 20 id from Employee e ';
if(@State is not null)
set @cond = @cond + ' and e.state = @State'
if(@Industry is not null)
set @cond = @cond + ' and e.industry = @Industry'
IF len(@cond) > 0
SET @sql = @sql + ' WHERE ' + RIGHT(@cond, LEN(@cond)-3)
从Here
获取的动态查询提示