I have a big performance Problem with my Query: I use Java Spring boot 3.1.1 with JDBCTemplate.
My Program executes this Query on MSSQL Server:
DECLARE @P0 Integer;
DECLARE @P1 Integer;
DECLARE @P2 Integer;
SET @P0 = 1476;
SET @P1 = 1476;
SET @P2 = 1476;
select
*
from
SL.dbo.t024 WITH (READPAST)
JOIN SL.dbo.t023 WITH (READPAST) ON t024.c011 = t023.c010
JOIN SL.dbo.t346 WITH (READPAST) ON t023.c004 = t346.c002
where
t024.mesoyear = @P0
AND t023.mesoyear = @P1
AND t346.mesoyear = @P2
AND (t024.c014 = 1 OR t024.c014 = 0)
AND (t024.c038 IS NULL OR t346.c002 <> '999')
Order BY
t346.c002,
t024.c002
It takes 8 seconds to finish! BUT when i change the Statement (in MSSQL Studio) to:
select
*
from
SL.dbo.t024 WITH (READPAST)
JOIN SL.dbo.t023 WITH (READPAST) ON t024.c011 = t023.c010
JOIN SL.dbo.t346 WITH (READPAST) ON t023.c004 = t346.c002
where
t024.mesoyear = 1476
AND t023.mesoyear = 1476
AND t346.mesoyear = 1476
AND (t024.c014 = 1 OR t024.c014 = 0)
AND (t024.c038 IS NULL OR t346.c002 <> '999')
Order BY
t346.c002,
t024.c002
then it takes 0 seconds to finish!
on the first Satement with Variables the MSSQL Studio Execution plan says that he didn't find the indexes, bu on the second statement he find the indexes and it is very fast! WHY??
The next one i find is that when i add OPTION (RECOMPILE) to the end of the first Query with Variable so the Query finishes in 0 seconds.
So what's the problem here? How can i solve this? i cannot test every query for OPTION (RECOMPILE) is needed!
the same could happen also with JPA and Hibernate... I dont know where the issue is! OR how i can solve this without OPTION (RECOMPILE)