這個問題的問題here如何計算在T-SQL年齡年,月,日,時,分,秒和毫秒
我試圖擴大丹麥人的回答的延伸,但結果是有點問題。
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
幫助將不勝感激!
您提供的代碼不能處理所有正確的案例。例如,試一下,dateFrom:'2014-04-24 13:59:00'dateTo:'2014-04-24 14:01:00' –