Search code examples
sqlsql-servercasewhere-clausesql-like

"cased" where, multiple values for one when


Sorry if the title is weird, I can't think of a better one to explain the situation. "WHERE/CASE" part of the query, as of now:

where CO_SEGMENT LIKE case (outsideVar)
    when 9999 then '%'
    when 9001 then '9002' --9013, 9014, 9015
    when 9003 then '901[345]'
    when 9004 then '900[56]'
    when 9007 then '900[89]'
    else (outsideVar)
end

The idea is I have a list of products, and a list of segments, which groups products. My problem is for some segments cause I need them to list products from "like-conflicted" segments.

From that example above, segment 9001 contains segments 9002 and 9003 - but 9003 is a 'fake segment', he contains segments 9013 thru 9015. I can't put 90[01][2345] because it would include products from segment 9005 on the list, which don't belong there...

Tips?

PS: I'll only be able to see this on Monday, so happy hew year, folks!


Solution

  • There are two different ways to use CASE, try the other way.

    WHERE CASE
        WHEN outsideVar = 9999 THEN CO_SEGMENT LIKE '%'
        WHEN outsideVar = 9002 THEN (CO_SEGMENT LIKE '9002' OR CO_SEGMENT LIKE '901[345]')
        WHEN outsideVar = 9003 THEN CO_SEGMENT LIKE '901[345]'
        WHEN outsideVar = 9004 THEN CO_SEGMENT LIKE '900[56]'
        WHEN outsideVar = 9007 THEN CO_SEGMENT LIKE '900[89]'
        ELSE CO_SEGMENT LIKE outsideVar
        END