Date Calculations

Occasionally, you may find that you need to start with a date value and use it to calculate some other date. For example, your SQL code might need to determine what date is the first day of the month or last day of the month. As you may know, working with the datetime data type in SQL Server can be a bit of a challenge. You probably already know how to use the datepart() function to extract specific components of a date (for example, year, month, day). You can then use those components along with a number of functions to calculate a date that you might need. This section provides some examples of algorithms you can use to generate some commonly needed date values.

The DATEDIFF function calculates the difference between two ...

Get Microsoft® SQL Server 2008 R2 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.