2
I have a Storedprocedure that unfortunately only because of an IF has ceased to be a select and turned everything into a VARCHAR statement and then I run it, losing one of the main benefits of MSSQL which is the compilation.
I modified the SP only 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 you see the @Idcorretor <> 0 parameter I should add a Where clause
I usually use sp_executesql when sending an array, so I command it in text format and concatenate everything by assembling a string and executing it...
– Dorathoto
Your code seems to work, but I still don’t understand how it actually worked.
– Dorathoto
Basically I passed the logic of IF into the query. Yours IF says: "if the reported broker is non-zero, then select the results based on this broker". My OR does more or less the same thing: "bring the correctors equal to the parameter or, if the parameter is zero, it does not matter the corrector". I was able to explain?
– Caffé
Yes, thank you. It would be nice to post the code as it was: ALTER PROCEDURE [dbo]. [stp_Admin14_listagem_impressao]
 @ intacao int,
 @ IDCorretor int
 AS
 BEGIN


SELECT * from exemplo
 WHERE intacao = @intacao
AND (@IDCorretor = 0 OR tbl_imoveis.int_CORRETOR = (@IDCorretor))
– Dorathoto
the Where clause was wrong at the end pq you cast, I used the cast only for concatenation conversion... intacao = @intacao AND (@Idbroker = 0 OR tbl_imoveis.int_CORRETOR = (@Idbroker))
– Dorathoto
@Dorathoto Certo. I was really weirded out by these Casts but I didn’t want to get into the merit :-)
– Caffé