请考虑采用某些参数的以下示例过程。存储过程中可选参数的最佳解决方案
Create Procedure CustomerSearch(
@Name nVarChar(100) = Null,
@Phone nVarChar(100) = Null,
@Address nVarChar(100) = Null,
)
As
Select *
From dbo.CustomerView
Where (@Name is Null or Name = @Name) And
(@Phone is Null or Phone = @Phone) And
(@Address is Null or Address = @Address)
因为参数的值可能为空,所以我找到两个解决方案来处理它。
- 使用或contition这样的: (@Name为空或名称= @Name)
- 使用动态SQL,并添加条件进行查询,如果参数值不为空。
在CustomerView视图中存在多个表连接,并且此表具有大量数据并且性能非常重要。解决方案1有开销(执行计划)。由于某些原因,我无法使用动态sql。有更好的方法来建立这个查询?
当我使用条件@Name是Null或Name = @Name)而不是Name = @Name并查看执行计划时,索引查找成本增加。
您可能会发现此资源有用:[T-SQL中的动态搜索条件](http://www.sommarskog.se/dyn-search.html)。 –