0
I am working on migrating an API to a new platform and this includes migrating queries that were previously written directly into the code to functions in the database. One of the problems I’ve been facing is that some checks we did in the code are not available in SQL Server (or I don’t know how to do them).
I need to put a condition of where
depending on the value of a variable. For example:
DECLARE @var AS INT = 10;
SELECT * FROM TB_SQL
WHERE col1 = 'StackOverflow'
IF(@VAR = 1) THEN
BEGIN
AND col2 = @var
END
ELSE
BEGIN
-- não coloca condição nenhuma
END
In that case, the condition AND col2 = @var
would only be included in the query if the value of @var was 1.
Is there any way to do that?
The way you’re doing
@var
will always be10
. Where do you pull the value to set the@var
?– rbz
You can’t put one
if
so in thewhere
, you can use the conditional functioniif()
orcase
for example– Ricardo Pontual
@Rbz this was just an example that I quickly created to not expose company data. The value of
@var
, in the case, comes from a POST request.– Renan Lazarotto
@Ricardopontual using the
iif()
I can do it within afunction
?– Renan Lazarotto
I didn’t quite understand, you say use
iif
within a Function, or use Function within theiif
?– Ricardo Pontual
Use the
iif
within afunction
. But based on your answer below, I think I’ve managed to solve my problem. I’m just going to do a few more tests to see if it’s really solved.– Renan Lazarotto