在SQL Server中,与NULL日期进行比较会得到NULL值。

huangapple go评论52阅读模式
英文:

comparison with NULL date gives NULL value in SQL Server

问题

这段代码会返回一个datetime值。

英文:

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

答案1

得分: 0

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
英文:

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

huangapple
  • 本文由 发表于 2023年3月31日 19:39:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898117.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定