两个日期之间的差异以及如果一个日期为空,则使用SQL中的当前日期

时间:2017-02-10 16:02:55

标签: sql sql-server time

我必须找到两个合约日期之间的差异。基本上在生效日期和结束日期之间。但是,如果合同仍然存在,那么我想要今天。(时间戳)?我如何在SQL中结合使用 例如:

start d: 1/1/17 end date: 2/1/17 effective days 31
start d: 1/1/17 end date: null  effective days: total days to date.

2 个答案:

答案 0 :(得分:2)

Error: listen EADDRINUSE :::21000

答案 1 :(得分:0)

您可以使用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

在简单检查值是否为case时,您还可以使用两个速记函数null和{{1}中的一个,而不是使用稍微冗长的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