开发者

If..Else or Case in WHERE Clause - something different

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 po开发者_StackOverflow中文版ssible! Any help/suggestions would be greatly appreciated.

I'm trying to build a conditional WHERE clause based on

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

Is this possible?


Just do WHERE (@CustomerID = 0 OR CustID = @CustomerID)


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


The most common way of simulating an IF-ELSE statement in sql are CASE and DECODE (in oracle at least): Ex pseudocode:

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;

DECODE: select decode(x,1,y,2,z) example from dual;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜