DATEPART

The SQL DATEPART function is a useful tool for extracting specific parts of a date or time value in SQL Server. It allows you to retrieve the year, month, day, hour, minute, second, or millisecond portion of a datetime value.

Syntax

The syntax of the DATEPART function is as follows:

DATEPART(datepart, date)

Here, datepart specifies the part of the date or time you want to extract, and date is the datetime value from which you want to extract the specified part.

Examples

For example, to extract the year from a datetime value, you can use the following query:

SELECT DATEPART(year, '2023-04-27 10:30:00');

This will return the value 2023, which is the year portion of the datetime value.

Similarly, to extract the month portion, you can use the following query:

SELECT DATEPART(month, '2023-04-27 10:30:00');

This will return the value 4, which is the month portion of the datetime value.

Some other examples of using the DATEPART function include:

SELECT DATEPART(day, '2023-04-27 10:30:00'); 
-- returns 27

SELECT DATEPART(hour, '2023-04-27 10:30:00'); 
-- returns 10

SELECT DATEPART(minute, '2023-04-27 10:30:00'); 
-- returns 30

SELECT DATEPART(second, '2023-04-27 10:30:00');
-- returns 0

SELECT DATEPART(millisecond, '2023-04-27 10:30:00.123'); 
-- returns 123

Overall, the SQL DATEPART function is a powerful and flexible tool for extracting specific parts of date or time values in SQL Server.