I am trying to achieve conditional join like this
declare @JoinWithT2 bit = 1; select T1.* from T1 inner join T2 on (@JoinWithT2 = 0 or T1.Id=T2.Id) This works fine, when I pass @JoinWithT2 value 1 it gives me result using the join of both the tables, and when I pass @JoinWithT2 value 0 it returns all the results from T1 ignoring the join.
This is all working good but I am concerned about the performance because the above can also be achieved like this
if @JoinWithT2=0 begin select T1.* from T1 end else begin select T1.* from T1 inner join T2 on (T1.Id=T2.Id) end What is the best way to achieve conditional join, first one or the second?
I personally feel second one should be better for performance as it does not involve T2 at all while the first query may be using T2
@JoinWithT2is 0, the first query is not equivalent toselect T1.* from T1- instead, it becomes an implicit cartesian join - see sqlfiddle.com/#!3/3f574/3@JoinWithT2value is 0