Case in SQL

  • Is there a better way to approach this ? Sorry there was an error earlier .

    Case when Server_Excluded <> 'Yes' and Aged30 > 0 Then 'Green'

    when Server_Excluded <> 'Yes' and Group= '' then 'Amber'

    when Server_Excluded <> 'Yes' and ImportantAged30 >0 Then 'Amber'

    End as Status

  • That seems fine to me. An alternative could be:

    Case when Server_Excluded <> 'Yes' and Aged30 > 0 Then 'Green'

    when Server_Excluded <> 'Yes' and (Group= '' OR ImportantAged30 >0) Then 'Amber'

    End as Status

    I can't say that one is better than the other, it's mainly based on your preferences.

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2
  • I see. Thank you

  • What is Server_Excluded = 'Yes'? In other words, don't forget the ELSE.

  • You could also use nested CASE functions to avoid repeating the Server_Excluded test.

    CASE WHEN Server_Excluded <> 'Yes' THEN

    CASE WHEN Aged30 > 0 THEN 'Green'

    WHEN Group = '' OR ImportantAged30 > 0 THEN 'Amber' END

    END

    It's a matter of style preference, I doubt there's any measurable performance difference.

    The main consideration I would use is which version looks easier to understand and maintain.

  • Just to know, how many possible values do you have for the Server_Excluded column? Does it allow NULLs, as well?

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply