I have a large SQL query with multiple statements and UNION ALL. I am doing something like this now:
DECLARE @condition BIT;
SET @condition = 0;
SELECT * FROM table1
WHERE @condition = 1;
UNION ALL
SELECT * FROM table2
In this case, table1 won’t return any results. However, that query is complex with many joins (such as FullTextTable). The execution plan’s estimate shows a high cost, but the actual number of rows and time to execute seems to show otherwise. Is this the most efficient way of filtering a whole query, or is there a better way? I don’t want anything in the first select to run, if possible.
The best way to solve this is by using Dynamic SQL. The problem with DForck’s solutions is that it may lead to parameter sniffing. Just to give a rough idea, your query might look something like this
DECLARE @query VARCHAR(MAX);
IF (@condition = 0)
SET @query = ‘SELECT * FROM table1
UNION ALL ‘
SET @query = @query + ‘SELECT * FROM table2’
sp_executesql @query
This is just a simplified case, but in actual implementation you would parameterize the dynamic query which will solve the problem of parameter sniffing. Here is an excellent explanation about this problem Parameter Sniffing (or Spoofing) in SQL Server