I have a StoredProcedure that unfortunately only because of an IF it stopped being a select and turned everything into a VARCHAR statement and then I execute it, losing one of the main benefits of MSSQL being compiled.
I modified SP just to illustrate the problem:
ALTER PROCEDURE [dbo].[stp_Admin14_listagem_impressao]
@intacao int,
@IDCorretor int
AS
BEGIN
declare @query nvarchar(max)
set @query = 'SELECT * from exemplo
WHERE intacao = '+ cast(@intacao as varchar) +')
--// #### AQUI é o problema, o que fazer???
if (@IDCorretor <> 0)
BEGIN
set @query = @query + ' AND tbl_imoveis.int_CORRETOR = ' + cast(@IDCorretor as varchar)
END
exec sp_executesql @query
END
In short, if the @IDCorretor ; 0 should I add a clause where