Quantcast
Channel: Cranky Bit » Microsoft
Viewing all articles
Browse latest Browse all 20

Backward Use of CASE in SQL

$
0
0

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.


Viewing all articles
Browse latest Browse all 20

Trending Articles