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