Skip to content
Advertisement

How to only run left join when the variable is not null?

I’m trying to simplify my stored procedure and I have one that is only using left join based on the user id that is passed in. If the user id is null, don’t do left join, but if it is null, left join it with another table. How should I re-write it ? Thank you

Advertisement

Answer

Currently your stored procedure return different number columns depending on the @UserId.

You may remove the IF condition, and combined it as one single query by moving ru.UserId = @UserId to ON condition. This will make it a true LEFT JOIN to table RoomUser.

This will means it always return 4 columns as result

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement