简体   繁体   中英

CASE expression for NULL condition is not working

I have an SQL query where the case expression is not working because I am getting the NULL value.

Any idea how to fix this?

select 
td.reportEndDate,
    CASE td.originalLinearAirDate
    WHEN NULL THEN '12345678'
    END As originalLinearAirDate
from 
FROM DBA.Telecast td 
where id = 2
order by
td.reportEndDate,
originalLinearAirDate;

You can use COALESCE() :

SELECT td.reportEndDate, 
       COALESCE(td.originalLinearAirDate, '12345678') AS originalLinearAirDate -- Use default date instead of '12345678'
FROM DBA.Telecast td 
WHERE id = 2
ORDER BY td.reportEndDate, originalLinearAirDate;

In your case expression you didn't specified ELSE part hence you got NULL .

However, case expression will only return one type. So, you should check code or do necessary conversation.

You can use isnull

select 
td.reportEndDate,
    CASE WHEN td.originalLinearAirDate IS NULL THEN '19000101'
         ELSE td.originalLinearAirDate 
    END As originalLinearAirDate
from 
FROM DBA.Telecast td 
where id = 2
order by
td.reportEndDate,
originalLinearAirDate;

The problem is the NULL comparison. The comparison is never true, even when used from comparison in a CASE expression.

If you wanted to do this using CASE , then you need to use IS NULL :

(CASE WHEN td.originalLinearAirDate IS NULL
      THEN '12345678'
 END) As originalLinearAirDate

If you want to return the original value in this case, you need an ELSE :

(CASE WHEN td.originalLinearAirDate IS NULL
      THEN '12345678'
      ELSE td.originalLinearAirDate 
 END) As originalLinearAirDate

Note that this will return an error if the column is really a DATE , because '12345678' cannot be converted to a date.

This version is better expressed using COALESCE() :

COALESCE(td.originalLinearAirDate, '12345678')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM