I am writing a stored procedure and when I tested the procedure in Execution Plan/Sentry Plan Explorer I have noticed that in one statement the plan reacts strangely.
Here are 2 scripts that from my point of view are the same, but the results are significantly different.
Script 1 (not real code, but a code that demonstrates the problem):
DECLARE @MyVariable INT;
SET @MyVariable = 123456789;
SELECT MT.Name, OT.Name
FROM MyTable MT
INNER JOIN OtherTable OT ON MT.ID = OT.MyTableID
WHERE OT.TypeID = @MyVariable;
Script 2:
SELECT MT.Name, OT.Name
FROM MyTable MT
INNER JOIN OtherTable OT ON MT.ID = OT.MyTableID
WHERE OT.TypeID = 123456789;
It seems to be the same, but the results I get are different:
- Estimated rows in Script 1: 15621 rows (wrong for sure, too many rows)
- Estimated rows in Script 2: 205 rows (logical result, probably true)
I think that the SQL execution plan behaves differently when a variable is used in the where
clause. Why? Or what is going on here? How to improve this?
Thanks