I want to be able to inner join two tables based on the value of a column I’m selecting.
My Query:
SELECT varA, varB, MAX(varC) varC
FROM table1
INNER JOIN table2 ON varB = table2.varB
INNER JOIN @tempTable ON varA = table1.column
INNER JOIN table3 ON varC = table3.column AND table3.column2 = 1 -- **IF NOT varA = 100**
INNER JOIN table4 ON varC = table4.column **-- IF varA = 100**
LEFT OUTER JOIN table5 ON table2.column = table5.column AND table5.column2 = 1 AND table5.column3 = 4
GROUP BY varB, varA
So, in short INNER JOIN on table4 if value of column(varA) is not 100 else INNER JOIN on table3
I think this will get the result you’re after:
Basically allows a join to either table, but only return rows where one of those joins found a record. If you want to return the actual columns from the table as part of the select then you could use an ISNULL:
EDIT: I should have added that you can’t conditionally join to tables unless you want to use dynamic SQL. You can either join to the table or not. What I outlined above lets you do the join to both tables and then check that one of them did join (which is basically what an Inner Join does).