Let's say I have a stored procedure that will execute complex logic when the @ComplicatedSearch = 1 parameter. When it is set to 1, I populate the @ValidIds variable table @ValidIds valid lines that this procedure can return. When it is 0, the logic bypasses, and we do not need to filter the returned rows.
So, skipping this logic, I get the following statement:
SELECT m.* ,a.* FROM MyTable m INNER JOIN AdditionalInfoTable a ON m.Id = a.MyTableId WHERE (@ComplicatedSearch = 0 OR EXISTS(SELECT * FROM @ValidIds WHERE Id = m.Id))
This works great; however, I believe that it would be more efficient to attach MyTable to @ValidIds, if applicable, against using EXISTS() , especially when MyTable contains a large number of lines.
Is there a way to do something like the one below, without recording a few requests? (the actual query is very large, so having multiple versions with and without merging will not be ideal)
SELECT m.* ,a.* FROM MyTable m ONLY DO THIS IF ComplicatedSearch = 1 PLEASE: INNER JOIN @ValidIds v ON m.Id = v.Id INNER JOIN AdditionalInfoTable a ON m.Id = a.MyTableId
source share