'Setting DateTime variable as NULL in CASE expression
I have two DateTime columns Date1 and Date2. If Date1 is populated, Date2 carries the same value, otherwise Date2 carries its own unique value.
What I am trying to do is, if Date1<>NULL, Date2=NULL.
I am using a CASE statement within a SELECT Statement that fetches other values as well. But its not solving my issue.
CASE
WHEN (DATE1<>NULL AND DATE2<>NULL)
THEN DATE2=NULL
ELSE DATE2
END
Help appreciated! Thanks
Solution 1:[1]
You should use IS NULL / IS NOT NULL for comparison
and in case when don't use assignment as DATE2 = NULL .. use just NULL
CASE WHEN (DATE1 IS NOT NULL AND DATE2 IS NOT NULL) THEN NULL ELSE DATE2 END
Solution 2:[2]
Use COALESCE function, it returns the first not-null argument which is what you're trying to do:
SELECT COALESCE(DATE1, DATE2) AS DATE2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ScaisEdge |
| Solution 2 | Salman A |
