SQL Server 2005:如何减去6个月

时间:2010-10-14 12:14:42

标签: sql sql-server-2005 datetime date datediff

我有约会,假设今天约会

declare @d datetime
set @d = '20101014'

我需要

select @d - <six month>

其中包含过去六个月的实际天数,从@d开始。

2 个答案:

答案 0 :(得分:46)

您可以使用DATEADD

select DATEADD(month, -6, @d)

编辑:如果您需要最多6个月前的天数,可以使用DATEDIFF

select DATEDIFF(day, @d, DATEADD(month, -6, @d))

答案 1 :(得分:1)

同时检查一下(开发这个主题):

我需要根据条件选择algorythm - 如果两个日期之间有多少天,就像6个月(从最后一个日期开始)。

我是这样做的:

    case
      when
        DATEDIFF(day, DATEADD(month, -6, @pDateEnd), @pDateEnd)
        >
        DATEDIFF(day, @pDateBegin, @pDateEnd)
      then 'there is no 6-month difference between two dates'
      else 'there is 6-month difference ore more between two dates'
    end