I have to compare 2 separate columns to come up with the most recent date between them. I am using DATEDIFF(minute, date1, date2) to compare them, however, in some records the date is Null, which returns a null result and messes up the CASE.
Is there a way around this, or a way to predetermine which date is null up front?
(psudocode)
UPDATE TABLE
SET NAME = p.name,
NEW_DATE = CASE WHEN DATEDIFF(minute,d.date1,d.date2) <= 0 THEN d.date
ELSE d.date2
END
FROM TABLE2 d
INNER JOIN TABLE3 p
ON d.ACCTNUM = p.ACCTNUM
The same is true for any comparisons with NULL under the ANSI Standard; whether you are comparing NULL to a CHAR, INT or any other value, variable or table column. Rule #2: In ANSI SQL, NULL is not equal to anything, even other NULLs! Comparisons with NULL always result in UNKNOWN.
DATEDIFF() With Wrong Date ValuesIf either of the date in the DATEDIFF() function is wrong or invalid, then the DATEDIFF() function returns NULL.
SQL Server IS NULL / IS NOT NULL Because the NULL value cannot be equal or unequal to any value, you cannot perform any comparison on this value by using operators such as '=' or '<>'.
Null Values can be replaced in SQL by using UPDATE, SET, and WHERE to search a column in a table for nulls and replace them. In the example above it replaces them with 0.
You can just add extra logic into your CASE:
UPDATE TABLE
SET NAME = p.name,
NEW_DATE = CASE
WHEN d.date1 IS NULL THEN -- somewhat
WHEN d.date2 IS NULL THEN -- somewhat
WHEN DATEDIFF(minute,d.date1,d.date2) <= 0 THEN d.date
ELSE d.date2
END
FROM TABLE2 d
INNER JOIN TABLE3 p
ON d.ACCTNUM = p.ACCTNUM
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With