计算两个日期之间相差几年几月几日。

DECLARE @s DATETIME,
        @e DATETIME

SET @s='2011-9-10'
SET @e='2014-9-10'

IF @e >= @s
  SELECT Cast(CASE
                WHEN Cast(Datepart(mm, @e) AS VARCHAR) + RIGHT('00' + Cast(Datepart(dd, @e) AS VARCHAR), 2) >= Cast(Datepart(mm, @s) AS VARCHAR) + RIGHT('00' + Cast(Datepart(dd, @s) AS VARCHAR), 2) THEN Datediff(yy, @s, @e)
                ELSE Datediff(yy, @s, @e) - 1
              END AS VARCHAR) + '年' + Cast(CASE
                                             WHEN Datepart(dd, @e) >= Datepart(dd, @s) THEN Datediff(mm, @s, @e)%12
                                             ELSE
                                               CASE
                                                 WHEN Datepart(mm, @s) = Datepart(mm, @e) THEN 11
                                                 ELSE Datediff(mm, @s, @e)%12 - 1
                                               END
                                           END AS VARCHAR) + '月' + Cast(CASE
                                                                          WHEN Datepart(dd, @e) >= Datepart(dd, @s) THEN Datediff(dd, Dateadd(mm, Datediff(mm, @s, @e), @s), @e)
                                                                          ELSE Datediff(dd, Dateadd(mm, Datediff(mm, @s, @e) - 1, @s), @e)
                                                                        END AS VARCHAR) + '日' AS '年龄'
ELSE
  SELECT '开始日期不能大于结束日期' AS error 



你可能感兴趣的:(数据库)