Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

comparison with NULL date gives NULL value in SQL Server

This code results in NULL. sale_jan_dt and sale_feb_dt both datetime columns.

s.sale_feb_dt = 2022-09-01 01:19:00.000
s.sale_jan_dt = NULL

select
    case 
        when s.sale_jan_dt >= s.sale_feb_dt
            then cast(convert(char(20), s.sale_feb_dt, 20) as datetime)             
        else
            cast(convert(char(20), s.sale_jan_dt, 20) as datetime) 
    end as min_sales_month
from sales s

Would this code return a datetime value or string? I have to use the min_sales_month in date calculations.

select
    case 
        when isnull(s.sale_jan_dt, '2100-12-31 23:59:59') >= s.sale_feb_dt
            then cast(convert(char(20), s.sale_feb_dt, 20) as datetime) 
            else cast(convert(char(20), s.sale_jan_dt, 20) as datetime) 
    end as min_sales_month
from 
    sales s

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can change comparison, swap result, and I believe you’ll get what you want.

select
    case 
        when s.sale_jan_dt >= s.sale_feb_dt or s.sale_jan_dt is null
            then cast(convert(char(20), s.sale_feb_dt, 20) as datetime)             
        else
            cast(convert(char(20), s.sale_jan_dt, 20) as datetime) 
    end as min_sales_month
from sales s
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading