I have a table that looks like this:
id1 | id2 | value | id3
1 | abc | 23 | apt-1
1 | abc | 24 | apt-2
2 | def | 25 | apt-3
3 | def | 25 | apt-3
I need to get the first rows from the table above that match a table valued parameter like this:
id1 | id2 |
1 | abc |
2 | def |
I want the result to be
id1 | id2 | value | id3
1 | abc | 23 | apt-1
2 | def | 25 | apt-3
Instead I get back three rows in the table.
id1 | id2 | value | id3
1 | abc | 23 | apt-1
1 | abc | 24 | apt-2
2 | def | 25 | apt-3
How do I fix this? What would be the efficiency of this? This is an interim solution for when we write more data than currently being read, but will be reading based on id3 too in the future.
Let's call the table Foo, and the tvp tvpInput.
I tried the following two queries:
--Approach 1
SELECT *
FROM Foo as ret
INNER JOIN @tvpInput t
ON
t.id1 = ret.id1
AND t.id2 = ret.id2
--Approach 2
SELECT *
FROM Foo AS ret
WHERE EXISTS
(
SELECT t.id1, t.id2 FROM @tvpInput t
WHERE
ret.id1 = t.id1
AND ret.id2 = t.id2
)