Definition and usage
The DATEPART () function is used to return a separate part of a date/time, such as year, month, day, hour, minute, and so on.
Grammar
DATEPART (Datepart,date)
The date parameter is a valid day expression. The datepart parameter can be the following value:
| DatePart |
Abbreviations |
| Years |
YY, yyyy |
| Quarter |
QQ, Q |
| Month |
MM, M |
| The day of the year |
Dy, y |
| Day |
DD, D |
| Week |
WK, WW |
| Week |
DW, W |
| Hours |
hh |
| Minutes |
MI, n |
| Seconds |
SS, S |
| Milliseconds |
Ms |
| Subtle |
MCs |
| Na-Sec |
Ns |
Instance
Suppose we have the following "Orders" table:
| OrderId |
ProductName |
OrderDate |
| 1 |
' Computer ' |
2008-12-29 16:25:46.635 |
We use the following SELECT statement:
SELECT DATEPART (yyyy,orderdate) as Orderyear,datepart (mm,orderdate) as Ordermonth,datepart (Dd,orderdate) as Orderdayfrom orderswhere OrderId=1
Results:
| OrderYear |
OrderMonth |
Orderday |
| 2008 |
12 |
29 |
SQL Server DATEPART () function