sql server - SQL do inner join if condition met -
i want way improve sql code, have use inner join when condition met. replicates code:
@systemmerge bit if (@systemmerge=1) begin select ....... mytable inner join table on table.param1=mytable.param1 inner join systemtable on systemtable.param2=mytable.param2 end else begin select ....... mytable inner join table on table.param1=mytable.param1 end
and in way this:
@systemmerge bit begin select ....... mytable inner join table on table.param1=mytable.param1 ***//the next 4 lines not working, pseudo of want:*** if (@systemmerge=1) begin inner join systemtable on systemtable.param2=mytable.param2 end
edit: solution (thanks @damien_the_unbeliever):
left join systemtable on systemtable.param2=mytable.param2 ((@systemmerge=1 , systemtable.param2 not null) or (@systemmerge=0 or @systemmerge null))
this should (approxmately) same thing:
select ....... mytable inner join table on table.param1=mytable.param1 left join systemtable on systemtable.param2=mytable.param2 , @systemmerge = 1 (@systemmerge = 0 or systemtable.nonnullablecolumn not null)
of course, means other references columns within systemtable
must written expect such columns null
.
Comments
Post a Comment