0

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:

enter image description here

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.

enter image description here

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' enter image description here

When variable = 'All', I should get table A i.e.

enter image description here

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 :)

4

2 回答 2

0

你有没有尝试过类似的东西

SELECT  A.*
FROM    [dbo].[your_table] A
WHERE   EXISTS  (
            SELECT  1
            FROM    [dbo].[your_table_2] B
            WHERE   A.City_Code = B.City_Code
        )
OR  @a = 'All'
于 2013-06-15T08:45:28.573 回答
0

你试过case语句吗?CASE 或 DECODE 通常类似于 SQL 中的 IF-ELSE 语句。

于 2013-06-15T09:56:05.533 回答