I've scenario like, I have to add my participate in conditional
e.g. When value is 1 then inner join to table a and when value 2 then inner join to table
below is my sample query and i'm getting error Incorrect syntax close to the keyword 'inner'
DECLARE @i INT=1 select name from emp if(@i=1) begin inner join a on a.ID=emp.ID end else if(@i=1) begin inner join b on b.ID=emp.ID end where emp.ID=2
Would the work? Outer join both tables both in conditions and set the conditional inside your choose clause like so:
select name, case when @i=1 then a.column else b.column end from emp left outer join a on a.ID=emp.ID left outer join b on b.ID=emp.ID where emp.ID=2
While you discovered the construct is against the law in SQL. An IF statement can't be incorporated inside a DML query. It's possible to, however, write two separate queries (presenting along the way a little of duplication) and also have either conditionally selected.
DECLARE @i INT SET @i=1 if(@i=1) begin select name from emp inner join a on a.ID=emp.ID where emp.ID=2 end else if(@i=2) begin select name from emp inner join b on b.ID=emp.ID where emp.ID=2 end
see if this helps