Jan Jan - 5 months ago 12
SQL Question

Using "If" condition in where clause

I like to use "IF" condition in where clause. From various threads, I understand that one of the options is CASE expression but I couldn't figure it out.

Sample Code :

select * from sampleTable
where
If @taxtype = 'P' then
(taxtype = 'P' or (taxtype = 'E' and code in ('MER','SER')))
Else
(taxtype = 'E' and code not in ('MER','SER'))
End If


Any help is greatly appreciated.

Thank you!

Answer
select * from sampleTable
where 
  case when @taxtype = 'P' then
    (taxtype = 'P' or  (taxtype = 'E' and code in ('MER','SER')))
  Else
    (taxtype = 'E' and code not in ('MER','SER'))
  end

Looks like this'll work with Postres