question:
The same piece of code, running in a stored procedure is dozens of times slower than ordinary SQL execution
principle:
In SQL Server there is a feature called "Parameter sniffing" parameter sniffing. SQL Server will formulate an execution plan before the stored procedure is executed, resulting in slower speed.
Solution:
1. Create a variable in the stored procedure to replace the parameter
CREATE PROC sp_yp_jxctj @varTemp1 VARCHAR ( 50 ) AS BEGIN -- replace parameters with variables to prevent "Parameter sniffing" problems DECLARE @var1 VARCHAR ( 50 ) = @varTemp1 -- references to parameters below refer to @var1 , don't quote @varTemp1 END;
2. Hide the affected SQL statements, such as:
a) Put the affected sql statement in a sub-stored procedure, for example, we can call a word stored procedure after @thedate is set to today and pass in @thedate as a parameter.
b) Use sp_executesql to execute the affected sql. The execution plan will not be executed unless the sp_executesql statement is executed.
c) Use dynamic sql ("EXEC(@sql)" to execute the affected sql.