While OPTION(RECOMPILE) would probably solve your issue, I would suggest reading this article: https://www.sqlinthewild.co.za/index.php/2009/09/15/multiple-execution-paths/ which explains why if/else blocks in a stored procedure can mess with your query execution, and how you can fix it.