是否可以在datediff中使用datepart?

时间:2015-03-15 13:02:06

标签: sql sql-server sql-server-2008

是否可以在datediff中使用datepart

  SELECT   datediff (YEAR,2015 ,(datepart(YEAR,Person.DateOfBirth))) AS Exp from Person

请帮帮我

2 个答案:

答案 0 :(得分:0)

datediff的参数应该是日期,例如:

datediff(year, '20150101', Person.DateOfBirth)

使用年份时,请记住它跟踪年份的变化,因此不适合计算年龄,例如

select datediff(year, '20150101', '20150201')

返回0,但

select datediff(year, '20141231', '20150201')

返回1.

答案 1 :(得分:0)

是, 但形成这样......

datediff(result In(Year/Month/Day),toDate,Fromdate)
  

' 2015'在约会中是2015-01-01'

尝试:select CAST('2015' as date)

SELECT datediff(YEAR,'2015',Person.DateOfBirth) AS Exp from Person--result in year 
SELECT datediff(Month,'2015',Person.DateOfBirth) AS Exp from Person--result in month 
SELECT datediff(Day,'2015',Person.DateOfBirth) AS Exp from Person--result in day