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:
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
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `MyTable` ADD INDEX `mytable_idx_id` (`ID`);
ALTER TABLE `OtherTable` ADD INDEX `othertable_idx_typeid` (`TypeID`);
SELECT
MT.Name,
OT.Name
FROM
MyTable MT
INNER JOIN
OtherTable OT
ON MT.ID = OT.MyTableID
WHERE
OT.TypeID = 123456789