在where子句中使用“If”条件

时间:2014-02-24 23:58:08

标签: 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

非常感谢任何帮助。

谢谢!

2 个答案:

答案 0 :(得分: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

Looks like这适用于Postres

编辑:

留下我的原始答案,因为要点可以工作,但Postgres doesn't have a concept of variables和其他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;

这是显示

SQL Fiddle

答案 1 :(得分:3)

看起来你可以通过添加OR

来做到这一点
select * from sampleTable
where 
  (
    @taxtype = 'P' 
    AND
    (taxtype = 'P' or  (taxtype = 'E' and code  in ('MER','SER')))
  )
  OR
  (
    taxtype = 'E' 
    AND 
    code in ('MER','SER')
  )

如何使用案例陈述(为了解决手头的问题)的一个例子。这适用于SQL Server

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