AND 1=(when when @flag=1 then 1 when (@flag=2 and b.Id is not null) then 1 when (@flag=3 and b.Id is null) then 1 else 2 end)