SQL WHERE 子句中的 If..Else 或 Case - 一些不同的东西
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6528000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
If..Else or Case in WHERE Clause - something different
提问by Rich
I've read loads of q&a's on here but none fit the bill for what I'm trying to achieve. I don't even know if this is possible! Any help/suggestions would be greatly appreciated.
我在这里阅读了大量问答,但没有一个符合我想要实现的目标。我什至不知道这是否可能!任何帮助/建议将不胜感激。
I'm trying to build a conditional WHERE
clause based on
我正在尝试建立一个WHERE
基于条件的条款
CustID (int) = @CustomerID
If @CustomerID = 0
then I want the result to be WHERE CustID > 0
(i.e. return all customers) otherwise I only want certain customers CustID = @CustomerID
如果@CustomerID = 0
那么我希望结果是WHERE CustID > 0
(即返回所有客户)否则我只想要某些客户CustID = @CustomerID
Is this possible?
这可能吗?
回答by antlersoft
Just do WHERE (@CustomerID = 0 OR CustID = @CustomerID)
只需执行 WHERE (@CustomerID = 0 OR CustID = @CustomerID)
回答by Hector Sanchez
something like this?
像这样的东西?
SELECT *
FROM YOURTABLE
WHERE
( CASE
WHEN @CustomerID = 0 THEN CustID
ELSE 1
END
) > 0
AND
( CASE
WHEN @CustomerID <> 0 THEN @CustomerID
ELSE CUSTID
END
) = CUSTID
回答by J. Bend
The most common way of simulating an IF-ELSE statement in sql are CASE and DECODE (in oracle at least): Ex pseudocode:
在sql中模拟IF-ELSE语句最常用的方法是CASE和DECODE(至少在oracle中):Ex伪代码:
if (x == 1) then y; else if (x == 2) then z; end if
if (x == 1) then y; else if (x == 2) then z; end if
CASE:
select
case x
when 1 then y
when 2 then z
end example
from dual;
案件:
select
case x
when 1 then y
when 2 then z
end example
from dual;
DECODE:
select decode(x,1,y,2,z) example from dual;
解码:
select decode(x,1,y,2,z) example from dual;