英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论