Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

SQL Server DATEPART() function

SQL Server DATEPART() function


SQL Dates SQL Server Date Functions


Definition and Usage

The DATEPART() function is used to return a single part of a date/time, such as year, month, day, hour, minute, and so on.

Syntax

DATEPART(datepart,date)

The date parameter is a valid date expression. The datepart parameter can be one of the following values:

datepart Shorthands
Year yy, yyyy
Quarter qq, q
Month mm, m
Day of year dy, y
Day dd, d
Week wk, ww
Week dw, w
Hour hh
Minute mi, n
Second ss, s
Millisecond ms
Microsecond mcs
Nanosecond ns

Example

Suppose we have the following "Orders" table:

OrderId ProductName OrderDate
1 Jarlsberg Cheese 2008-11-11 13:23:44.657

The following is the SELECT statement:

SELECT DATEPART(yyyy,OrderDate) AS OrderYear,

DATEPART(mm,OrderDate) AS OrderMonth,

DATEPART(dd,OrderDate) AS OrderDay,

FROM Orders

WHERE OrderId=1

The result is as follows:

OrderYear OrderMonth OrderDay
2008 11 11

SQL Dates SQL Server Date Functions