Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 possible! 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?

like image 946
Rich Avatar asked Jun 29 '11 22:06

Rich


2 Answers

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

like image 55
antlersoft Avatar answered Nov 01 '22 16:11

antlersoft


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
like image 43
Hector Sanchez Avatar answered Nov 01 '22 16:11

Hector Sanchez