This SQL Server tutorial explains how to use the DATEPART function in SQL Server (Transact-SQL) with syntax and examples.
Description
In SQL Server (Transact-SQL), the DATEPART function returns a specified part of a given date, as an integer value.
Syntax
The syntax for the DATEPART function in SQL Server (Transact-SQL) is:
DATEPART( interval, date )
Parameters or Arguments
interval
The time/date interval that you wish to retrieve from date. It can be one of the following values:
Value (any one of) | Explanation |
---|---|
year, yyyy, yy | Year interval |
quarter, qq, q | Quarter interval |
month, mm, m | Month interval |
dayofyear | Day of year interval |
day, dy, y | Day interval |
week, ww, wk | Week interval |
weekday, dw, w | Weekday interval |
hour, hh | Hour interval |
minute, mi, n | Minute interval |
second, ss, s | Second interval |
millisecond, ms | Millisecond interval |
dateThe date to use to retrieve the interval value.
Note
- The DATEPART function returns the result as an integer value.
- The DATENAME function returns the result as a string value.
Applies To
The DATEPART functions can be used in the following versions of SQL Server (Transact-SQL):
- SQL Server 2017, SQL Server 2016, SQL Server 2014, SQL Server 2012, SQL Server 2008 R2, SQL Server 2008, SQL Server 2005
Example
Let’s look at some SQL Server DATEPART functions examples and explore how to use the DATEPART functions in SQL Server (Transact-SQL).
For example:
SELECT DATEPART(year, '2014/04/28'); Result: 2014 SELECT DATEPART(yyyy, '2014/04/28'); Result: 2014 SELECT DATEPART(yy, '2014/04/28'); Result: 2014 SELECT DATEPART(month, '2014/04/28'); Result: 4 SELECT DATEPART(day, '2014/04/28'); Result: 28 SELECT DATEPART(quarter, '2014/04/28'); Result: 2 SELECT DATEPART(hour, '2014/04/28 09:49'); Result: 9 SELECT DATEPART(minute, '2014/04/28 09:49'); Result: 49 SELECT DATEPART(second, '2014/04/28 09:49:12'); Result: 12 SELECT DATEPART(millisecond, '2014/04/28 09:49:12.726'); Result: 726
Pingback: SQL Server: DATENAME Function - Adglob Infosystem Pvt Ltd
Pingback: SQL Server: DAY Function - Adglob Infosystem Pvt Ltd
Pingback: SQL Server: MONTH Function - Adglob Infosystem Pvt Ltd
Pingback: SQL Server: YEAR Function - Adglob Infosystem Pvt Ltd