Make an IF to set WHERE

Asked

Viewed 66 times

2

I need help with a command in a proc SQL.

Basically I need something like this:

...
...

WHERE

IF ( @Id_ProductClass IS NULL  )
    WHERE CLIENTPROD.Id_ProductClass NOT IN (59, 150)
ELSE
    WHERE CLIENTPROD.Id_ProductClass = @Id_ProductClass

It’s possible to do something like this?

1 answer

2

Include the condition of if in WHERE itself, thus:

WHERE
    (
        (@Id_ProductClass IS NOT NULL AND CLIENTPROD.Id_ProductClass = @Id_ProductClass)
        OR (@Id_ProductClass IS NULL AND CLIENTPROD.Id_ProductClass NOT IN (59, 150))
    )
    -- se não houver mais condições aqui, pode remover os parênteses mais externos.

Or concatenate a string and use the stored sp_executesql to execute it, as did the AP in this another question.

When choosing to concatenate the query into a string, do not use parameters, as suggested in reply of that same question.

  • I’ve used a similar example instead of using IF. Very good answer.

  • It worked just right. Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.