简介:我们在sql中经常要判断年或者月或者日是否相等,我们可以用datediff函数,使用很方便
datediff:判断年或月或日或周、星期、小时、分钟等的差别数
使用格式:
DATEDIFF(datepart,startdate,enddate)
日(天数差别):可用day 也可以用下列的代码替换
DATEDIFF(day,'2008-12-29','2008-12-30') AS DiffDate --结果为1
SELECT DATEDIFF(day,'2008-12-30','2008-12-29') AS DiffDate --结果为-1
月(月的差别):可用month 也可用下列代码替换
SELECT DATEDIFF(MM,'2008-12-30','2010-12-29') AS DiffDate --结果为24
年(年的差别天数):可用year 也可用下列代码替换
SELECT DATEDIFF(year,'2008-12-30','2010-12-29') AS DiffDate --结果为2
SELECT DATEDIFF(yy,'2008-12-30','2010-12-29') AS DiffDate --结果为2