I have this query(of course with couple joins across tables and some views which I will call x for simplicity).
- Case 1 :
select * from x
-> returns in 10 sec, still acceptable, fairly heavy on joins and lot of data - Case 2 :
select * from x where userid = 1
-> returns in 0-1 sec, good enough Case 3 : using SP :
if @userid = -1 select * from x else select from x where userid = @userid
-> now calling sp with paramenter userid 1 should return on 0-1 sec as it should be comparable to case 2 but in fact it returns in 10 sec.Now, parameter masking OR WITH RECOMPILE on sp OR OPTION (recompile) on query with where clause doesn't help, What makes the SP run faster with
userid = something
is putting OPTION(recompile) on the first part of the SP ie on the query without where clause. :- Case 4 : using SP :
if @userid = -1 select * from x option (recompile) else select * from x where userid = @userid
Any explanation?
I can guess earlier it was using optimization based of query without where clause even for the query with where clause, but why is that?