May 21, 2012 by Christoff Truter SQL
A while ago one of our clients reported a bit of a peculiar performance problem when accessing a certain report
in one of their systems. Generally they could retrieve the report in no time, but all of a sudden it took about
3 minutes to retrieve a relatively small amount of data.
Strangely enough the older entries for this report could still be retrieved almost instantly.
So I went through all the motions to find a solution and analyzed the database, found it to be terribly
designed and poorly maintained. The developer didn't even bother to create indexes for any of the foreign keys.
Like a good Jedi I added the appropriate indexes for the
appropriate fields, but that just made things worse, it now oddly enough even took longer to retrieve data.
I decided to have a look at the guilty stored procedure only to astonishingly find that the
stored procedure runs super fast within SSMS (SQL Server Management Studio).
At this point I got up and phoned an exorcist, they came out and prayed over the source code and anointed the server
while a bunch of scary looking evil spirits seeped out of the sides of the server box like toxic gases.
CREATE PROCEDURE [dbo].[ProcedureName] @Param1 DATETIME, @Param2 DATETIME AS BEGIN DECLARE @LocalParam1 DATETIME DECLARE @LocalParam2 DATETIME SET @LocalParam1 = @Param1 SET @LocalParam2 = @Param2 -- Logic END
CREATE PROCEDURE [dbo].[ProcedureName] @Param1 DATETIME, @Param2 DATETIME WITH RECOMPILE AS BEGIN -- Logic END
CREATE PROCEDURE [dbo].[ProcedureName] @Param1 DATETIME, @Param2 DATETIME AS BEGIN SELECT * FROM SometTable WHERE SomeDate BETWEEN @Param1 AND @Param2 OPTION (RECOMPILE) END
CREATE PROCEDURE [dbo].[ProcedureName] @Param1 DATETIME, @Param2 DATETIME AS BEGIN SELECT * FROM SometTable WHERE SomeDate BETWEEN @Param1 AND @Param2 OPTION (OPTIMIZE FOR (@Param1 = '2012/02/02')) END
CREATE PROCEDURE [dbo].[ProcedureName] @Param1 DATETIME, @Param2 DATETIME AS BEGIN SELECT * FROM SometTable WHERE SomeDate BETWEEN @Param1 AND @Param2 OPTION (OPTIMIZE FOR (@Param1 UNKNOWN, @Param2 UNKNOWN)) END