How can I do the following in SQL Server
DECLARE @Local nvarchar(20)
SET @Local = 'True'
SELECT * FROM My_Table
WHERE my_ID IN
(IF @Local = 'True'
SELECT AllIDs FROM ATable
ELSE
SELECT TeamIDs FROM TeamTable
)
The optimizer will optimize away the wrong query, so the performance will as that of the corresponding (remaining) query.
Don't do this!
(at least not if you care about performance)
There is certainly a way of doing this, but you really shouldn't - the reason being that (in general) a single statement has only 1 execution plan, however you essentially have 2 (potentially very different) requests:
Combining these two queries means that SQL server is forced to try and optimise both of these at the same time using only 1 exectuion plan. Depending on how different the two tables are this might work fine, or it might go horrily horrily wrong.
For example, if
ATable
contains only 1 row, whileTeamTable
contains all of the ids inMy_Table
then SQL server has to choose / compromise between doing a lookup (best if usingATable
) and a table scan (best if usingTeamTable
) - whatever it ends up doing it's not possible for SQL server to execute both queries using the optimal execption plan (unless both execution plans happen to be the same).You should use 2 statements instead:
In fact in this particular case you might be better off selecting the list of ID's into a temporary table instead.
Go for a union :-