在where子句中使用"If"条件

Jan*_*Jan 2 sql postgresql

我喜欢在where子句中使用"IF"条件.从各种线程,我理解其中一个选项是CASE表达式,但我无法弄清楚.

示例代码:

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
Run Code Online (Sandbox Code Playgroud)

任何帮助是极大的赞赏.

谢谢!

Bra*_*rad 6

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
Run Code Online (Sandbox Code Playgroud)

看起来这将适用于Postres

编辑:

留下我的原始答案,因为要点有效,但Postgres没有像其他RDBMS那样的变量概念所以我重新写了这个

WITH myconstants as (SELECT 'P'::text as vtaxtype)

select * from sampleTable
where 
  case when (select vTaxType from myconstants) = 'P' then
    (taxtype = 'P' or  (taxtype = 'E' and code in ('MER','SER')))
  Else
    (taxtype = 'E' and code not in ('MER','SER'))
  end;
Run Code Online (Sandbox Code Playgroud)

这是一个SQL小提琴显示