这个问题是这里问题的延伸
我试图扩展 Dane 的答案,但结果有点问题。
DECLARE @dateFrom DATETIME
DECLARE @dateTo DATETIME
DECLARE @tmpdate DATETIME
DECLARE @years INT
DECLARE @months INT
DECLARE @days INT
DECLARE @hours INT
DECLARE @minutes INT
DECLARE @seconds INT
DECLARE @milliseconds INT
SELECT @dateFrom = '2011-01-01 11:24:38:100'
SELECT @dateTo = '2012-01-01 11:24:38:110'
SELECT @tmpdate = @dateFrom
SELECT @years = DATEDIFF(yy, @tmpdate, @dateTo)
- CASE WHEN (MONTH(@dateFrom) > MONTH(@dateTo)) OR (MONTH(@dateFrom) = MONTH(@dateTo) AND DAY(@dateFrom) > DAY(@dateTo))
THEN 1
ELSE 0
END
SELECT @tmpdate = DATEADD(yy, @years, @tmpdate)
SELECT @months = DATEDIFF(mm, @tmpdate, @dateTo) - CASE WHEN DAY(@dateFrom) > DAY(@dateTo) THEN 1 ELSE 0 END
SELECT @tmpdate = DATEADD(mm, @months, @tmpdate)
SELECT @days = DATEDIFF(dd, @tmpdate, @dateTo)
SELECT @tmpdate = DATEADD(dd, @days, @tmpdate)
SELECT @hours = DATEDIFF(hh, @tmpdate, @dateTo)
SELECT @tmpdate = DATEADD(hh, @hours, @tmpdate)
SELECT @minutes = DATEDIFF(mi, @tmpdate, @dateTo)
SELECT @tmpdate = DATEADD(mi, @minutes, @tmpdate)
SELECT @seconds = DATEDIFF(ss, @tmpdate, @dateTo)
SELECT @tmpdate = DATEADD(ss, @seconds, @tmpdate)
SELECT @milliseconds = DATEDIFF(ms, @tmpdate, @dateTo)
SELECT
@years AS [years]
, @months AS [months]
, @days AS [days]
, @hours AS [hours]
, @minutes AS [minutes]
, @seconds AS [seconds]
, @milliseconds AS [milliseconds]
结果是:
years months days hours minutes seconds milliseconds
1 0 0 0 0 0 10
但是当我运行时:
SELECT @dateFrom = '2011-01-02 11:24:38:110'
SELECT @dateTo = '2012-01-01 10:23:37:100'
结果是:
years months days hours minutes seconds milliseconds
0 11 30 -1 -1 -1 -10
帮助将不胜感激!