使用DATEDIFF函数,用法如下:
The DATEDIFF function calculates the period of time in dateparts between the second and first of two dates you specify. In other words, it finds an interval between two dates. The result is a signed integer value equal to date2 - date1 in date parts.
The following query uses the date November 30, 2001, and finds the number of days that elapsed between DueDate
and that date:
USE AdventureWorks; GO SELECT DATEDIFF(day, DueDate, 'Nov 30 2001') FROM Sales.SalesOrderHeader; GO |
For the rows in SalesOrderHeader
that have having a DueDate
of October 21, 1995, the result produced by the last query is 40. (There are 40 days between October 21 and November 30.) To calculate an interval in months, use the following query:
USE AdventureWorks; GO SELECT interval = DATEDIFF(month, DueDate, 'Nov 30 2001') FROM Sales.SalesOrderHeader; GO |
The query produces a value of 1 for the rows with a DueDate
in October and a value of 5 for the rows with a DueDate
in June.
When the first date in the DATEDIFF function is later than the second date specified, the resulting value is negative.
If one or both of the date arguments is a smalldatetime value, they are converted to datetime values internally for the calculation. Seconds and milliseconds in smalldatetime values are automatically set to 0 for calculation.
这是从MSDN上摘抄,其实你可以自己到微软官方的MSDN上找找相关资料