Question

What I'm trying to do is write a query which, based on a boolean will select rows which satisfy two conditions or at least one of the two.

The following is a simplified query that gets the job done. Thing is, the where clause in my query is much more complex so I'm looking for a way to rewrite it in a more readable fashion.

Is this possible?

declare @AndParam bit
set @AndParam = 1

SELECT * FROM Table

  Where 
  (@AndParam = 1
  AND
  (Table.CategoryID = 3 
  AND
  Table.Age < 30))

  OR

  (@AndParam = 0
  AND
  (Table.CategoryID = 3 
  OR
  Table.Age < 30))

EDIT:
This question really is about readability and esthetics.
In the stead of Table.Age < 30 there are five additional checks including subqueries. Practically, this means that I have a large section of the code duplicated with only one difference; The And/Or.
Seeing as how SQL can be difficult to read I'm looking to fix it up.

Was it helpful?

Solution

Maybe something like this:

Where
   CASE WHEN Table.CategoryID = 3 THEN 1 ELSE 0 END +
   CASE WHEN Table.Age < 30 THEN 1 ELSE 0 END -- + more CASEs for each condition
   >=
      CASE WHEN @AndParam = 1 THEN 2 ELSE 1 END
      --For more conditions, change 2 above to however many conditions there are

You basically make each condition give you a 1 or 0, and then add all of these up - then you do a final check, depending on @AndParam on whether you hit the total number of conditions or just at least 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top