Backward Use of CASE in SQL

I was updating an old app to use SQL on a new SQL Server database rather than an older Access database. As any database programmer is aware, there are irritating inconsistencies between Access SQL and SQL Server's T-SQL, such as absence of the IIF() and Trim() functions in T-SQL.

So I was going through the SQL and making these changes. I came across a very ugly IIF() function similar to this:

SQL:
  1. IIF(phLead=True,'LEAD',
  2. IIF(phFax=True,'FAX',
  3. IIF(phVVM=True,'VVM', 'DEPT')))

Take that statement and add even more boolean fields. Clearly, the intent was to have a calculated field that had a friendly name based on which boolean field was true.

So, how can this be easily converted into a CASE statement? As it stands, CASE statements are actually more verbose than the IIF() function, and the IIF() function above is already hard to read and verbose as it is.

A direct code conversion would be something like this:

SQL:
  1. CASE phLead WHEN 1 THEN 'LEAD'
  2. ELSE CASE phFax WHEN 1 THEN 'FAX'
  3. ELSE CASE phVVM WHEN 1 THEN 'VVM'
  4. ELSE 'DEPT' END END END

Ugly, ugly, ugly. The cool thing about CASE that differs from IIF() is that you can attack it from the other direction. Instead of saying, "Is phLead true? Is phFax true? Is phVVM true?", you can instead say, "Okay, who's true? phLead? phFax? phVVM?" It sounds negligible, but the code is shorter and easier to read:

SQL:
  1. CASE 1 WHEN phLead THEN 'LEAD'
  2. WHEN phFax THEN 'FAX'
  3. WHEN phVVM then 'VVM'
  4. ELSE 'DEPT' END

Ahh, much better.

4 Responses to “Backward Use of CASE in SQL”

  1. todd sharp Says:

    Technically you don’t even need the 1 in your last example. There are two different flavors of CASE (as you’ve illustrated) - a simple case and a searched case. Here’s what the docs show:

    Simple CASE function:
    CASE input_expression
    WHEN when_expression THEN result_expression
    [ …n ]
    [
    ELSE else_result_expression
    ]
    END

    Searched CASE function:

    CASE
    WHEN Boolean_expression THEN result_expression
    [ …n ]
    [
    ELSE else_result_expression
    ]
    END

  2. Josh Says:

    Thanks! I never realized this alternate syntax existed until a need like this called for it.

  3. todd sharp Says:

    Funny - there was a long time that I didn’t know the “simple” method existed a while back! :)

  4. Josh Says:

    Lol! When I first read about CASE statements in SQL way back when, it resonated with my understanding of SWITCH..CASE statements in C. Until this situation, I never even considered that the SQL equivalent would work any other way.

Leave a Reply

  Theme Brought to you by Directory Journal and Elegant Directory.