T-SQL 101: #59 Extracting date and time components in SQL Server T-SQL using DATEPART

In an earlier post, I showed how you can use the YEAR, MONTH, or DAY functions to extract those parts of a date. But what if you want to extract any one of those other intervals?

Well, that's what the DATEPART function does. It allows us to specify the interval that we want to extract. Look at the following query examples:

And here are the results of that query:

First, I asked for the day, and this is no different to using the DAY function. I see 28 returned.

Next, I asked for the second, but because I only supplied a date, there were no second, and zero is returned.

Finally, I asked for the second in a datetime value that included seconds, so I get back the value 46 which is the seconds component of the time part of the value.

DATEPART is a useful function.

Learning T-SQL

It's worth your while becoming proficient in SQL. If you'd like to learn a lot about T-SQL in a hurry, our Writing T-SQL Queries for SQL Server course is online, on-demand, and low cost.

Leave a Reply

Your email address will not be published.