Stored Procedure taking time in execution

2019-08-15 11:50发布

问题:

I am breaking my head on this issue since long. I have stored procedure in MS SQl and when I try to execute that procedure by providing all the parameters in SQL Query, it takes long time to execute but when I try to directly run the query which is there in SP it executes in no time. This is affecting my application performance also as we are using stored procedures to fetch the data from DB Server.

Please help.

Regards,

Vikram

回答1:

Looks like parameter sniffing.

Here is a nice explanation: I Smell a Parameter!

Basically, sql server has cached query execution plan for the parameters it was first run with so the plan is not optimal for the new values you are passing. When you run the query directly the plan is generated at that moment so that's why it's fast.

You can mark the procedure for recompilation manually using sp_recompile or use With Recompile option in its definition so it is compiled on every run.