SQL Server DATEPART() Function

The DATENAME() function is a date and time function in Microsoft SQL Server used to extract a specific part of a date or time, such as the year, month, hour, or minute.

Syntax

DATEPART(datepart, date)

Parameter explanation:

  • datepart: The abbreviation or full name of the date or time part to be extracted from date. Common examples include year, quarter, month, dayofyear, day, week, weekday, hour, minute, second, millisecond, etc.
  • date: The date or time value from which to extract the date or time part.

Return value: The integer value of the specified date or time part.

Use Cases

The DATENAME() function is very useful in queries that require extracting specific parts from a date or time value. For example, it can be used to retrieve all the months from a date column.

Examples

Example 1: Extracting the Year

SELECT DATEPART(year, '2022-03-11') AS 'Year';

Output:

Year
2022

Example 2: Extracting the Month

SELECT DATEPART(month, '2022-03-11') AS 'Month';

Output:

Month
3

Conclusion

The DATENAME() function is a very useful function that allows users to extract specific parts from a date or time value. Using this function in data queries and report generation can greatly improve work efficiency and accuracy.