I am comparing two dates and trying to determine the max of the two dates. A null date would be considered less than a valid date. I am using the following case statement, which works – but feels very inefficient and clunky. Is there a better way?
update @TEMP_EARNED
set nextearn = case when lastoccurrence is null and lastearned is null then null
when lastoccurrence is null then lastearned
when lastearned is null then lastoccurrence
when lastoccurrence > lastearned then lastoccurrence
else lastearned end;
(This is in MS SQL 2000, FYI.)
Why does this work? if neither operand is null, then we get a “normal” comparison: the “then” branch when c1 > c2, the else branch when c1 <= c2.
On the “else” branch, we call coalesce, but as its first argument is the non-null c2, we return c2.
.
But if either operand is null, the test
c1 > c2evaluates to false, and we returncoalesce( c2, c1 ).If the null operand was c1, we get c2, which is what we want because we are (for this question) calling null is “less than” any non-null value.
If the null operand was c2, we get c1. That’s fine, because c1 is either not null, and thus (for this question) “greater than” the null c2, or…
If both operands were null, we get c1, but it doesn’t matter which we get, as both are null.