我正在尝试从DOB获取Age,Months,Hours,Minutes,Seconds,MilliSeconds,NanoSeconds但是在尝试获取毫秒或纳秒时出现错误:
Msg 535,Level 16,State 0,Line 3
日期函数导致溢出。分隔两个日期/时间实例的日期部分数量太大。尝试使用具有不太精确的日期部分的datediff。
我也试过转换方法来解决,但它不能 - 任何想法?
代码:
DECLARE @date datetime
SELECT @date = '2/11/1990 12:03:25.310 AM'
SELECT (DATEDIFF(yy, @date, GETDATE()) - CASE WHEN (MONTH(@date) > MONTH(GETDATE())) OR (MONTH(@date)
= MONTH(GETDATE()) AND DAY(@date) > DAY(GETDATE())) THEN 1 ELSE 0 END) AS "Age in Years",
(DATEDIFF(MONTH, @date, GETDATE()) - CASE WHEN DAY(@date) > DAY(GETDATE()) THEN 1 ELSE 0 END) AS "Months",
(DATEDIFF(DAY, @date, GETDATE())) AS "DAYS",
DATEDIFF(Hour,@date,GETDATE()) as [Hour],DATEDIFF(Minute,@date, GETDATE()) as [Minutes],DATEDIFF(Second,@date,GETDATE()) as [Seconds],
RIGHT(CONVERT(VARCHAR, @date, 100),2) AS "AM/PM",DATEDIFF(MILLISECOND,@date,GETDATE()) as MiliSeconds
答案 0 :(得分:4)
您试图在很长一段时间内以毫秒为单位获得结果并导致错误。
如果返回值超出int(-2,147,483,648到+2,147,483,647)的范围,则返回错误。 毫秒,startdate和enddate之间的最大差异为24天,20小时,31分钟和23.647秒。第二,最大差异是68年。
来源:http://msdn.microsoft.com/en-IN/library/ms189794.aspx
但是,我们有办法得到答案。
1 Sec = 1000 milliseconds.
1 Sec = 1000000000 nano seconds.
只需将结果以秒为单位转换为十进制,并转换为毫秒和纳秒。
DECLARE @date datetime
SELECT @date = '2/11/1990 12:03:25.310 AM'
SELECT (DATEDIFF(yy, @date, GETDATE()) - CASE WHEN (MONTH(@date) > MONTH(GETDATE())) OR (MONTH(@date)
= MONTH(GETDATE()) AND DAY(@date) > DAY(GETDATE())) THEN 1 ELSE 0 END) AS "Age in Years",
(DATEDIFF(MONTH, @date, GETDATE()) - CASE WHEN DAY(@date) > DAY(GETDATE()) THEN 1 ELSE 0 END) AS "Months",
(DATEDIFF(DAY, @date, GETDATE())) AS "DAYS",
DATEDIFF(Hour,@date,GETDATE()) as [Hour],DATEDIFF(Minute,@date, GETDATE()) as [Minutes],DATEDIFF(Second,@date,GETDATE()) as [Seconds],
RIGHT(CONVERT(VARCHAR, @date, 100),2) AS "AM/PM",
CAST(DATEDIFF(Second,@date,GETDATE()) AS DECIMAL) * 1000 AS MiliSeconds,
CAST(DATEDIFF(Second,@date,GETDATE()) AS DECIMAL) * 1000000000 AS NanoSeconds