[英]Using “If” condition in where clause
我喜欢在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
任何帮助是极大的赞赏。
谢谢!
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
看起来这将适用于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;
这是一个SQL小提琴显示
看起来你可以通过添加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')
)
如何使用case语句(为了手头的问题)这样做的一个例子。 这适用于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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.