我经常对 mssql 中哪种方式更快有疑问。
where @id is null or id = @id
或where isnull(@id,id)=id
问题出现是因为 mssql 中的 or 操作通常较慢。where id = 1 or id = 2
或where id in (1,2)
类似的。
我想在这个问题中收集更多有争议的解决方案,让您更好地优化sql代码。
我经常对 mssql 中哪种方式更快有疑问。
where @id is null or id = @id
或where isnull(@id,id)=id
问题出现是因为 mssql 中的 or 操作通常较慢。
where id = 1 or id = 2
或where id in (1,2)
类似的。
我想在这个问题中收集更多有争议的解决方案,让您更好地优化sql代码。
where @id is null or id = @id
或where isnull(@id,id)=id
- 工作同样缓慢。SQL Server 无法提前预测结果,@id is null
并计划扫描整个表(或索引)并检查每条记录的谓词。在音量表上 - 同样快。在大的上,它同样很慢,而且变慢的不是谓词的计算,而是 IO。where id = 1 or id = 2
或where id in (1,2)
在同一张表上给出相同的计划 - 它们都出现在带有一组谓词的查找中(如果有合适的索引,请参见下文),或者如果没有合适的索引,或者表足够小,则出现在扫描中.要求:
计划片: