且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

T-SQL与存储过程:存储过程与T-SQL的速度问题

更新时间:2022-11-24 21:09:54

在存储过程内进行相当复杂的查询之前,我曾遇到过这种情况.它根据几个可选参数(例如,人名,电话号码,邮政编码等)搜索了多个字段. SQL Server提出了该存储过程的执行计划,然后从此以后继续以相同的执行计划运行SP.因此,如果下次您需要使用与执行计划中指定的索引不同的索引,则SQL Server可能会忽略该索引并使用***索引.我解决这个问题的方法是将功能拆分为多个存储过程.然后,第一个SP会根据所传递的数据来调用其他SP之一.您还可以添加索引提示,以告诉SQL Server要使用哪些索引.
I''ve run into this before when I made a fairly complex query inside of a stored procedure. It searched multiple fields based on several optional parameters (e.g., person name, phone number, zip code, and so on). SQL Server comes up with an execution plan for that stored procedure, then continues to run the SP with the same execution plan from then on. So if the next time you need to use a different index than the one specified in the execution plan, SQL Server may ignore that and use the less optimal index. The way I got around this was to split the functionality into multiple stored procedures. The first SP then calls one of those other SP''s depending on the data it is passed. You can also add index hints to tell SQL Server which indexes to use.