您可以使用case 表达式将值相互比较,然后使用getdate() 等函数返回当前日期和时间。
select getdate() -- Will return the date and time of right now
,case when 1 < 2
then 'Less'
else 'Greater'
end -- This will return the value 'Less'
,case when YourDateField < getdate()
then YourDateField
else getdate()
end -- This will return the earliest of YourDateField or right now
在简单地检查值是否为null 时,不要使用稍微冗长的case,您还可以使用isnull 和coalesce 这两个速记函数之一。 isnull 只检查一个值,coalesce 从列表中返回第一个不是 null 的值(还有其他差异,但我会留给你研究):
select isnull(YourPopulatedDateField,getdate()) -- Will return YourPopulatedDateField
,isnull(YourNullDateField,getdate()) -- Will return right now
,coalesce(YourNullDateField,getdate()) -- Will return right now
,coalesce(YourNullDateField,OtherNullField, getdate()) -- Will also return right now
将其中之一与datediff 函数结合起来,可以为您提供其他 cmets 和答案所提供的内容:
-- Both of these will return the same result:
select datediff(day,
,StartDate
,coalesce(EndDate, getdate())
)
,datediff(day,
,StartDate
,isnull(EndDate, getdate())
)