在SQL-Server 2008中我该如何实现以下目标 -的if-else在where子句中的SQL服务器
select * from student
where
(
(if studentId is not null then studentId='x')
else
(firstName='abc' and age > 26)
)
我想避免重写整个SELECT子句的任何条件分开。
在SQL-Server 2008中我该如何实现以下目标 -的if-else在where子句中的SQL服务器
select * from student
where
(
(if studentId is not null then studentId='x')
else
(firstName='abc' and age > 26)
)
我想避免重写整个SELECT子句的任何条件分开。
你可以简单地在你的WHERE
子句中使用的OR
:
SELECT *
FROM student
WHERE
studentId = 'x'
OR (firstname = 'abc' AND age > 26)
您可以在where
子句中使用case
声明。你几乎可以认为case
语句,如SQL的 “一套基于” 一个if
声明的版本 -
select *
from student
where
case
when studentId is not null and studentId = 'x'
then 1
when firstName='abc' and age > 26
then 2
else 0
end <> 2
更多关于case
陈述书
我想你需要为OR的第二部分添加一个显式的'AND studentId为null'(假设我正确地阅读这个问题,括号看起来有点奇怪),但是,是的,这是ans WER。 –
@lc。 - 不,不需要。 UPD:对不起,同意 - 在这个特别的措词你是正确的。 –
@RogerWolf这取决于你如何阅读问题中的“else” –