2. Dateadd

The name of this function is even more self-explanatory than the previous one. The dateadd function is used for adding a time or date interval to a date.

As always, the syntax is easier to understand with examples.

DECLARE @mydate Date
SET @mydate = GETDATE()
SELECT DATEADD(MONTH, 1, @mydate) AS NextMonthNextMonth

The first parameter indicates the interval and second one is the number of intervals. The third parameter is the base value.

DATEADD(interval, number of intervals, date)

We can use other intervals as well.

DECLARE @mydate Date
SET @mydate = GETDATE()
SELECT DATEADD(WEEK, -2, @mydate) AS TwoWeeksBeforeTwoWeeksBefore

If you put a minus sign before the number of intervals, it subtracts the specified interval from the given date.

It is possible to add time-based intervals but we need to use a datetime variable.

DECLARE @mydate DateTime
SET @mydate = GETDATE()
'2021-08-23 00:10:17.287'

Continue reading: https://towardsdatascience.com/5-must-know-sql-functions-for-manipulating-dates-e3f46d737b26?source=rss—-7f60cf5620c9—4

Source: towardsdatascience.com