0

What I want to do is based on a condition switch between where clauses conditions.. is this possible?

This is an example, the actual procedure is much longer and I do not want to use if on select.

Is it possible?

declare @city varchar(100) = 'NY'

SELECT s.suppliers, o.order
FROM suppliers s
INNER JOIN orders o ON s.id = o.id
WHERE 
    CASE WHEN @city = 'NY' 
           THEN (s.SupplierName = o.SupplierName AND o.Row = 'New') 
         ELSE s.SupplierName = o.SupplierName 
    END
abatishchev
  • 98,240
  • 88
  • 296
  • 433
NoviceDeveloper
  • 1,270
  • 3
  • 15
  • 41

2 Answers2

2

I've done something similar to this before:

WHERE s.SupplierName = o.SupplierName 
AND
CASE WHEN @city = 'NY' AND o.Row = 'New' THEN 1
WHEN @city <> 'NY' THEN 1
ELSE 0 END = 1

You can get as complicated as you want, but watch what you do to keep the performance reasonable.

JBrooks
  • 9,901
  • 2
  • 28
  • 32
1

You don't need a case for this, and you can put the common condition in the ON clause:

SELECT s.suppliers, o.order
FROM suppliers s INNER JOIN 
     orders o
     ON s.id = o.id AND s.SupplierName = o.SupplierName
WHERE (@city = 'NY' AND o.Row = 'New') OR
      (@city <> 'NY');

This assumes that @city is not NULL. The logic is only slightly more complicated to include that possibility (although it seems unnecessary).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • wouldn't this pull the records for both conditions? I think it does... I want it to grab either when city is NY and Row New and if that is not the case then only when city is NY ... not both. – NoviceDeveloper Apr 01 '15 at 19:33
  • @NoviceDeveloper . . . This implements the logic that you are trying to express with your `case` expression. The `@city` variable only takes on one value for the execution of the query, so only on of the conditions is used on any given run. – Gordon Linoff Apr 01 '15 at 22:25