摘要:
下文讲述SQL中datediff函数的用途,如下所示:
datediff函数功能说明:
datediff用于返回两个日期之间的差值,返回单位可以为(年、月、日、小时、分钟、秒、毫秒等等)
下文通过举例的方式讲述datediff的用法,如下所示:
方法1:计算两个日期之间的天数
SELECT DATEDIFF(day, '2019-12-01', '2019-12-03')
AS [天数之差];
DECLARE @date1 datetime2 = '2019-12-01';
DECLARE @date2 datetime2 = DATEADD(year, 1, @date1);
SELECT
DATEDIFF( year, @date1, @date2 ) AS Years,
DATEDIFF( quarter, @date1, @date2 ) AS Quarters,
DATEDIFF( month, @date1, @date2 ) AS Months,
DATEDIFF( week, @date1, @date2 ) AS Weeks,
DATEDIFF( dayofyear, @date1, @date2 ) AS DayOfYear,
DATEDIFF( day, @date1, @date2 ) AS Days;
例3:返回两个日期之间的小时、分钟、秒信息
DECLARE @date1 datetime2 = '2012-12-08 00:00:00.0000000';
DECLARE @date2 datetime2 = DATEADD(hour, 1, @date1);
SELECT
DATEDIFF( hour, @date1, @date2 ) AS Hours,
DATEDIFF( minute, @date1, @date2 ) AS Minutes,
DATEDIFF( second, @date1, @date2 ) AS Seconds;
例4:返回两个日期之间的毫秒、微秒和纳秒数
DECLARE @date1 datetime2 = '2012-12-08 00:00:00.0000000';
DECLARE @date2 datetime2 = DATEADD(millisecond, 1, @date1);
SELECT
DATEDIFF( millisecond, @date1, @date2 ) AS Milliseconds,
DATEDIFF( microsecond, @date1, @date2 ) AS Microseconds,
DATEDIFF( nanosecond, @date1, @date2 ) AS Nanoseconds;
注意事项:
datediff返回值最大值为int,当两个日期之间的差值超过int的最大值,则无法返回相应的结果,并返回错误信息
此时我们需使用datediff_big函数代替datediff函数