Yuval A.
Yuval A.

Reputation: 6089

Using CASE for WHERE field IN

The following is not a "correct way" to do it, but rather a demonstration for what I'm trying to achieve:

SELECT
   [...]
FROM
   [...]
WHERE condition1 
  AND condition2 
  AND field IN CASE (@type)
                 WHEN 1 THEN (SELECT subquery #1)
                 WHEN 2 THEN (SELECT subquery #2)
                 WHEN 3 THEN (SELECT subquery #3)
               END

Meaning, I want a different sub-query for each different value for the parameter @type. What would be a good way to do it?

Upvotes: 3

Views: 881

Answers (3)

Bohemian
Bohemian

Reputation: 424993

Nice idea, but you have to split the tests like this:

Try this:

SELECT
   [...]
FROM
  [...]
WHERE condition1 
  AND condition2 
  AND CASE (@type)
        WHEN 1 THEN (field in (SELECT subquery #1))
        WHEN 2 THEN (field in (SELECT subquery #2))
        WHEN 3 THEN (field in (SELECT subquery #3))
    END

I've never tried this syntax before, so if it doesn't work, use rs's answer, which will work (I've used his type of syntax before). I hope this does work though, because it look more elegant - could you let me know if it works?

Upvotes: 1

BellevueBob
BellevueBob

Reputation: 9618

It's very hard to tell what you are trying to do, but considering the example provided, each of the three "subqueries" return some value which is compared to some other value in an IN clause. I'd investigate using an INNER JOIN instead:

SELECT
   [...]
FROM
   [...]

INNER JOIN (
   SELECT CASE WHEN @type = 1 THEN somefield
               WHEN @type = 2 THEN somefield
               WHEN @type = 3 THEN somefield
               END AS inner_field
   FROM [....]
   ) XTRA
ON XTRA.inner_field=field

WHERE
   condition1 AND condition2

Of course, this is just an illustration; you'd need to a version that matches your data. Whether you really need three separate sub-queries depends very much on what they are doing. the point is to use a JOIN, which most databases deal with very well.

Upvotes: 0

rs.
rs.

Reputation: 27427

Try this

SELECT
   [...]
FROM
   [...]
WHERE
   condition1 AND condition2 AND 
   ((@type = 1 and field IN (SELECT subquery #1))
    OR (@type = 2 and field IN (SELECT subquery #2))
    OR (@type = 3 and field IN (SELECT subquery #3))
   )

Upvotes: 7

Related Questions