Tuesday, November 19, 2013

SQL query runs fast but stored procedure equivalent runs slow

If a SQL stored procedure is running slow, but the query is quick, try declaring local variables to replace the parameters in the stored procedure.

* Not sure why this works, please leave a comment if you have any info.

Replace the stored procedure paramters with local variables

ALTER PROCEDURE [dbo].[SlowProcedure]
(
@PARAM_begindate SMALLDATETIME = NULL,
@PARAM_enddate SMALLDATETIME = NULL
)
AS
--Add @PARAM_ variables to speed up query

DECLARE @begindate SMALLDATETIME,
                  @enddate SMALLDATETIME

SELECT  @begindate = @PARAM_begindate,
                @enddate = @PARAM_enddate
...

SELECT *
FROM [Table]
WHERE Date BETWEEN @begindate AND @enddate

No comments: