I am trying to "short-circuit" an INNER JOIN, if condition isn't met.
What I tried:
I found that if a Left Join is preceded with a False clause on "ON" condition, the LEFT JOIN fails. Hence, I tried to simulate INNER JOIN with LEFT OUTER JOIN and WHERE clause got the execution plan as below:
DECLARE @a nvarchar(4) = 'All'
SELECT A.*
FROM [dbo].[your_table] A
LEFT JOIN [dbo].[your_table_2] B
ON @a <> 'All'
WHERE A.City_Code = CASE WHEN @a <> 'All'
THEN B.City_Code
ELSE A.City_Code END
This will "short-circuit" the left join and it will never occur. Execution plan is below:
But then when I tried to execute the same statement by declaring the variable as 'Al' and not 'All', I saw execution plan was still the same.
I am puzzled if Join happened in the initial step or not?
What I want:
I want to know whether the above approach is correct? Is it really short-circuiting the INNER JOIN?
I basically want the INNER JOIN to happen between the two tables only when variable is not 'All' else it should not JOIN and continue further. I have already tried by using "OR" (to short-circuit) and "IN" (to apply filter) but the performance slows down if you have too many items in IN clause.
Please help me and do tell me if I was wrong anywhere in my approach.
Sample Data:
I should get the INNER JOIN result only when variable <> 'all'
When variable = 'All', I should get table A i.e.
Note: I have simplified this query hence it appears that simple if statement can do. In actual I have 53 parameters that I need to check and run JOINS. Plus result set of one query must be joined with another i.e. I have several other JOIN conditions preceding this :)