I have the following SQL code below. It is taking forever to complete but if I run just the SELECT DISTINCT ID, ParentID FROM Y WHERE ID IN (3,4), it completes instantly.
DECLARE @table TABLE
(
ID int,
ParentID int
)
INSERT INTO @table
SELECT DISTINCT ID, ParentID FROM Y WHERE ID IN (3,4)
SELECT * FROM @table
What is going on, this makes no sense.
Try to use a temporary table instead. The table variable is optimized for one row only and assumes that is what it will be getting.
Read more here