I have a query that I am putting in to a stored procedure. When I run the query with local variables the query takes ~1 second to run. When I put the same query inside of a stored procedure and call the SP, it takes around 2 minutes to run.
From previous questions in SO I think it may be related to parameter sniffing. When I've had this issue before I have declared local variables inside my SP and then used the local variables throughout. This has worked in the past, but does not seem to help me in this case.
I currently have
CREATE PROCEDURE dbo.ProcedureName
@DIV VARCHAR(4),
@STD VARCHAR(1), -- S or N
@scen varchar(20)
AS
BEGIN
DECLARE
@DIV_copy VARCHAR(4),
@STD_copy VARCHAR(1),
@scen_copy varchar(20);
SELECT
@DIV_copy = @DIV,
@STD_copy = @STD,
@scen_copy = @scen;
I have also tried adding WITH RECOMPILE
like so
CREATE PROCEDURE dbo.ProcedureName
@DIV VARCHAR(4),
@STD VARCHAR(1), -- S or N
@scen varchar(20)
WITH RECOMPILE
AS
BEGIN
DECLARE
@DIV_copy VARCHAR(4),
@STD_copy VARCHAR(1),
@scen_copy varchar(20);
SELECT
@DIV_copy = @DIV,
@STD_copy = @STD,
@scen_copy = @scen;
Additionally, I have tried adding the OPTION(RECOMPILE)
at the end of my SP like so:
SELECT *
FROM #Output
OPTION(RECOMPILE)
END
GO
I also tried using:
OPTION(OPTIMIZE FOR UNKNOWN )
As well as:
OPTION(QUERYTRACEON 4136)
On this option, I do not have appropriate permissions for query tracing.
None of the 5 fixes above appear to fix the issue as the stored procedure still takes anywhere between 2 minutes and 2 minutes and 30 seconds for the same query that takes 1 or 2 seconds outside of the stored procedure.
These fixes all came from this article 'Different Approaches to Correct SQL Server Parameter Sniffing'
Has anyone had similar issues? Thank you for your time!
SQL Server 2008R2
I have tried adding the OPTION(RECOMPILE) at the end of my SP
- it should be placed after the offending query. But ifwith recompile
didn't work I doubt this correction will. – Certifiable